用一个哈希表 cnt 记录每个元素的剩余次数。构造答案时,如果元素 x 的剩余次数为 0,则将 x 从 cnt 中删除。
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: deffindMatrix(self, nums: List[int]) -> List[List[int]]: ans = [] cnt = Counter(nums) while cnt: ans.append(list(cnt)) for x in ans[-1]: cnt[x] -= 1 if cnt[x] == 0: del cnt[x] return ans
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public List<List<Integer>> findMatrix(int[] nums) { varcnt=newHashMap<Integer, Integer>(); for (int x : nums) cnt.merge(x, 1, Integer::sum); varans=newArrayList<List<Integer>>(); while (!cnt.isEmpty()) { varrow=newArrayList<Integer>(); for (varit= cnt.entrySet().iterator(); it.hasNext(); ) { vare= it.next(); row.add(e.getKey()); e.setValue(e.getValue() - 1); if (e.getValue() == 0) it.remove(); } ans.add(row); } return ans; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: vector<vector<int>> findMatrix(vector<int> &nums) { unordered_map<int, int> cnt; for (int x: nums) ++cnt[x]; vector<vector<int>> ans; while (!cnt.empty()) { vector<int> row; for (auto it = cnt.begin(); it != cnt.end();) { row.push_back(it->first); if (--it->second == 0) it = cnt.erase(it); else ++it; } ans.push_back(row); } return ans; } };
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcfindMatrix(nums []int) (ans [][]int) { cnt := map[int]int{} for _, x := range nums { cnt[x]++ } forlen(cnt) > 0 { row := []int{} for x := range cnt { row = append(row, x) if cnt[x]--; cnt[x] == 0 { delete(cnt, x) } } ans = append(ans, row) } return }