思路
利用哈希表存储每个数字出现的次数,然后循环遍历key值,将key值对应value值大于0的key值存入List,最后将List存入List
解题过程
当List为空时,不要存入List,否则会多一行空行
Code
class Solution {
public List<List<Integer>> findMatrix(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
boolean flag = true;
while (flag) {
flag = false;
List<Integer> t = new ArrayList<>();
for (int num : map.keySet()) {
if (map.get(num) > 0) {
t.add(num);
map.put(num, map.get(num) - 1);
flag = true;
}
}
if (t.size() != 0)
list.add(t);
}
return list;
}
}
作者:菜卷
链接:https://leetcode.cn/problems/convert-an-array-into-a-2d-array-with-conditions/solutions/3618676/zhuan-huan-er-wei-shu-zu-by-ashi-jian-ch-149w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。