2610. Convert an Array Into a 2D Array With Conditions
```java
class Solution {
public List<List<Integer>> findMatrix(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0)+1);
}
int maxCount = 0;
for (int value : map.values()) {
maxCount = Math.max(maxCount, value);
}
List[] result = new ArrayList[maxCount];
for (int i = 0; i < maxCount; i++) {
result[i] = new ArrayList<>();
}
for (int key : map.keySet()) {
for (int i = 0; i < map.get(key); i++) {
result[i].add(key);
}
}
List<List<Integer>> finalResult = new ArrayList<>();
for (int i = 0 ; i < result.length; i++) {
finalResult.add(result[i]);
}
return finalResult;
}
}
/*
T: O(n) + O(keysize()*count)
S: O(keysize()*count)
Input: nums = [1,3,4,1,2,3,1]
Output: [[1,3,4,2],[1,3],[1]]
Explanation: We can create a 2D array that contains the following rows:
- 1,3,4,2
- 1,3
- 1
All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.
It can be shown that we cannot have less than 3 rows in a valid array.
[1,3,4,1,2,3,1]
first find distinct number, use hashmap
1: 3
3: 2
4: 1
2: 1
loop hashmap to put to array
*/
```
Last updated