LeetCode 2610: Convert an Array Into a 2D Array With Conditions (Frequency Layering)
LeetCode 2610ArrayHash MapToday we solve LeetCode 2610 - Convert an Array Into a 2D Array With Conditions.
Source: https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/
English
Problem Summary
Build a 2D array from nums so each row has distinct values and all values are used.
Key Insight
If a value appears k times, it must occupy k different rows. So we can place its 1st copy in row 0, 2nd in row 1, and so on.
Algorithm
Count frequency with a hash map. For each value and count, append value to rows 0..count-1, creating rows when needed.
Complexity
Time: O(n), Space: O(n).
Reference Implementations (Java / Go / C++ / Python / JavaScript)
class Solution {
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);
List<List<Integer>> ans = new ArrayList<>();
for (Map.Entry<Integer, Integer> e : freq.entrySet()) {
int v = e.getKey(), c = e.getValue();
for (int i = 0; i < c; i++) {
if (i == ans.size()) ans.add(new ArrayList<>());
ans.get(i).add(v);
}
}
return ans;
}
}func findMatrix(nums []int) [][]int {
freq := map[int]int{}
for _, x := range nums { freq[x]++ }
ans := [][]int{}
for v, c := range freq {
for i := 0; i < c; i++ {
if i == len(ans) { ans = append(ans, []int{}) }
ans[i] = append(ans[i], v)
}
}
return ans
}class Solution {
public:
vector<vector<int>> findMatrix(vector<int>& nums) {
unordered_map<int,int> freq;
for (int x : nums) freq[x]++;
vector<vector<int>> ans;
for (auto &[v,c] : freq) {
for (int i = 0; i < c; ++i) {
if (i == (int)ans.size()) ans.push_back({});
ans[i].push_back(v);
}
}
return ans;
}
};class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
freq = Counter(nums)
ans = []
for v, c in freq.items():
for i in range(c):
if i == len(ans):
ans.append([])
ans[i].append(v)
return ansvar findMatrix = function(nums) {
const freq = new Map();
for (const x of nums) freq.set(x, (freq.get(x) || 0) + 1);
const ans = [];
for (const [v, c] of freq) {
for (let i = 0; i < c; i++) {
if (i === ans.length) ans.push([]);
ans[i].push(v);
}
}
return ans;
};中文
题目概述
把 nums 转成二维数组,要求每一行元素互不相同,并且用完全部元素。
核心思路
某个数字出现 k 次,就至少要占据 k 行。把第 1 次放第 0 行、第 2 次放第 1 行,依次类推即可满足“同一行不重复”。
算法步骤
先统计频次,再按出现次数把值分层放入结果行,行不够就新建。
复杂度分析
时间复杂度 O(n),空间复杂度 O(n)。
多语言参考实现(Java / Go / C++ / Python / JavaScript)
class Solution {
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);
List<List<Integer>> ans = new ArrayList<>();
for (Map.Entry<Integer, Integer> e : freq.entrySet()) {
int v = e.getKey(), c = e.getValue();
for (int i = 0; i < c; i++) {
if (i == ans.size()) ans.add(new ArrayList<>());
ans.get(i).add(v);
}
}
return ans;
}
}func findMatrix(nums []int) [][]int {
freq := map[int]int{}
for _, x := range nums { freq[x]++ }
ans := [][]int{}
for v, c := range freq {
for i := 0; i < c; i++ {
if i == len(ans) { ans = append(ans, []int{}) }
ans[i] = append(ans[i], v)
}
}
return ans
}class Solution {
public:
vector<vector<int>> findMatrix(vector<int>& nums) {
unordered_map<int,int> freq;
for (int x : nums) freq[x]++;
vector<vector<int>> ans;
for (auto &[v,c] : freq) {
for (int i = 0; i < c; ++i) {
if (i == (int)ans.size()) ans.push_back({});
ans[i].push_back(v);
}
}
return ans;
}
};class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
freq = Counter(nums)
ans = []
for v, c in freq.items():
for i in range(c):
if i == len(ans):
ans.append([])
ans[i].append(v)
return ansvar findMatrix = function(nums) {
const freq = new Map();
for (const x of nums) freq.set(x, (freq.get(x) || 0) + 1);
const ans = [];
for (const [v, c] of freq) {
for (let i = 0; i < c; i++) {
if (i === ans.length) ans.push([]);
ans[i].push(v);
}
}
return ans;
};
Comments