NeetCode #144LC-2610MediumArrays & Hashing
← Back to All Problems#144 · #2610 · Convert an Array Into a 2D Array With Conditions(转换二维数组)
📌 Problem Statement & Constraints
You are given an integer array
nums. Create a 2D array where the i-th row contains the i-th occurrence of each distinct value, and pad shorter rows with zeros so the array is rectangular. Constraints: 1 <= nums.length <= 200, 1 <= nums[i] <= nums.length.💡 Core Algorithmic Approaches
- Count the occurrences of each value.
- The number of rows equals the maximum frequency.
- For each distinct value, append it to the first
freqrows. - No zero padding is actually needed: the problem guarantees that the last row is fully populated, so the rows all end up the same length naturally.
💻 Benchmark Python3 Implementation
class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
from collections import Counter
cnt = Counter(nums)
rows = [[] for _ in range(max(cnt.values()))]
for v, c in cnt.items():
for i in range(c):
rows[i].append(v) # i-th occurrence goes to row i
return rows⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): counting plus distributing each occurrence once.
💾 Space Complexity
O(n) for the result.
⚠️ Interview Pitfalls & Follow-ups
- Adding explicit zero padding: unnecessary, since each row receives one entry per value that occurs at least that many times, and the last row is guaranteed complete.
- Sizing the row list by
len(nums): the number of rows is the maximum frequency, not the array length. - Appending to the same row for all occurrences: the
i-th occurrence must go to thei-th row. - Assuming values are unique: duplicates are the whole point of the problem.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
转换二维数组
给你一个整数数组 nums。请你创建一个满足以下条件的二维数组:① 二维数组应该只包含数组 nums 中的整数;② 二维数组中的每一行都包含 不同 的整数;③ 二维数组行数最少。返回结果数组。如果存在多种答案,则返回其中任何一种。约束:1 ≤ nums.length ≤ 200;1 ≤ nums[i] ≤ nums.length。
核心要点
- 按频次决定行数(核心洞察) :出现次数最多的那个值的频次即为所需的最小行数(因为同一个值必须分散到不同的行)。
- 分配策略 :对每个值 v,若它出现 c 次,就把它分别放入第 0 行到第 c−1 行。这样保证每行内同一值只出现一次,且总行数等于最大频次。
- 为什么行数不能再少 :设最大频次为 m,则该值需要 m 个不同的行,因此行数至少为 m;上述分配恰好达到 m,故最优。
- 实现 :用 Counter 统计频次,创建 m 个空行,对每个值 v 依次追加到前 c 行。
常见陷阱
- 行数取 len(set(nums)) :那是「不同值的个数」,不是最小行数。行数由 最大频次 决定。
- 按原数组顺序逐行填充而不看频次 :容易在同一行放入重复值,违反条件②。按频次分配到前 c 行是保证正确性的关键。
- 忘记 max(cnt.values()) 在 nums 非空时安全 :nums 至少一个元素,Counter 非空,因此 max 不会报错。
- 误以为需要把所有元素都塞进第一行 :每行必须无重复,因此同一值必须分散。
参考实现
from collections import Counter
class Solution:
def findMatrix(self, nums: list[int]) -> list[list[int]]:
cnt = Counter(nums)
rows = max(cnt.values()) # 最小行数 = 最大频次
res = [[] for _ in range(rows)]
for v, c in cnt.items():
for i in range(c):
res[i].append(v) # 分别放入前 c 行
return res