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-1All 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.
Input: nums =[1,2,3,4]Output: [[4,3,2,1]]Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.
To minimize the number of rows, we should distribute each occurrence of a number into different rows, so that each row contains only distinct numbers. The maximum frequency of any number determines the minimum number of rows needed.
classSolution {
public List<List<Integer>>findMatrix(int[] nums) {
Map<Integer, Integer> freq =new HashMap<>();
for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);
int rows = 0;
for (int v : freq.values()) rows = Math.max(rows, v);
List<List<Integer>> ans =new ArrayList<>();
for (int i = 0; i < rows; i++) ans.add(new ArrayList<>());
for (var e : freq.entrySet()) {
for (int i = 0; i < e.getValue(); i++) ans.get(i).add(e.getKey());
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funfindMatrix(nums: IntArray): List<List<Int>> {
val freq = mutableMapOf<Int, Int>()
for (x in nums) freq[x] = freq.getOrDefault(x, 0) + 1val rows = freq.values.maxOrNull() ?:0val ans = List(rows) { mutableListOf<Int>() }
for ((num, cnt) in freq) {
for (i in0 until cnt) ans[i].add(num)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deffindMatrix(self, nums: list[int]) -> list[list[int]]:
from collections import Counter
freq = Counter(nums)
rows = max(freq.values())
ans = [[] for _ in range(rows)]
for num, cnt in freq.items():
for i in range(cnt):
ans[i].append(num)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnfind_matrix(nums: Vec<i32>) -> Vec<Vec<i32>> {
use std::collections::HashMap;
letmut freq = HashMap::new();
for x in nums { *freq.entry(x).or_insert(0) +=1; }
let rows =*freq.values().max().unwrap();
letmut ans =vec![vec![]; rows];
for (&num, &cnt) in&freq {
for i in0..cnt { ans[i].push(num); }
}
ans
}
}