Open Zheaoli opened 2 years ago
class Solution {
public List<List<Integer>> groupThePeople(int[] groupSizes) {
int n = groupSizes.length;
List<List<Integer>> ans = new ArrayList<>();
//key为groupSizes[i],value为i集合,当value.size() == key时加入结果集
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
List<Integer> cur = map.getOrDefault(groupSizes[i], new ArrayList<>());
cur.add(i);
if (cur.size() == groupSizes[i]) {
ans.add(cur);
cur = new ArrayList<>();
}
map.put(groupSizes[i], cur);
}
return ans;
}
WeChat: Saraad
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/*
* @lc app=leetcode.cn id=1282 lang=cpp
*
* [1282] 用户分组
*/
// @lc code=start
class Solution
{
public:
vector<vector<int>> groupThePeople(vector<int> &groupSizes)
{
unordered_map<int, vector<int>> cache;
for (size_t i = 0; i < groupSizes.size(); i++)
{
cache[groupSizes[i]].push_back(i);
}
vector<vector<int>> res;
for (auto &&c : cache)
{
int count = c.second.size() / c.first;
for (size_t i = 0; i < count; i++)
{
vector<int> group;
for (size_t j = 0; j < c.first; j++)
{
group.push_back(c.second[i * c.first + j]);
}
res.push_back(group);
}
}
return res;
}
};
// @lc code=end
微信id: 而我撑伞 来自 vscode 插件
/*
* @lc app=leetcode id=234 lang=typescript
*
* [234] Palindrome Linked List
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
// type ListNode = {
// val: number;
// next: ListNode | null
// };
function isPalindrome(head: ListNode | null): boolean {
// put all linked list's value to a array
// const arr = [] as number[];
// let p = head;
// while(p) {
// arr.push(p.val);
// p = p.next;
// }
// let r = arr.length - 1;
// for (let l = 0; l < arr.length; l++) {
// if (arr[r] !== arr[l]){
// return false;
// }
// r--;
// }
// return true;
// create two pointer: slow and fast
// fast pointer moves two steps a time
// slow pointer moves one step a time
// at the end of loop, slow pointer would point to the middle of the linked list
// while the fast pointer point to the last element of the linked list
let slow = head;
let fast = head;
while(fast?.next) {
fast = fast.next.next;
slow = slow.next;
}
// reverse the second half of the linked list
// at the end of the loop, slow pointer would point to the last element of the linked list
let prev: any = null;
while(slow) {
const tmp = slow.next;
slow.next = prev;
prev = slow;
slow = tmp;
}
let left = head;
let right = prev;
while(right) {
if (right.val !== left.val) {
return false;
}
right = right.next;
left = left.next;
}
return true;
};
// @lc code=end
微信id: 弘树 来自 vscode 插件
2022-08-12