Skip to content

2610. Convert an Array Into a 2D Array With Conditions 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<vector<int>> findMatrix(vector<int>& nums) {
    // The number of rows we need equals the maximum frequency.
    vector<vector<int>> ans;
    vector<int> count(nums.size() + 1);

    for (const int num : nums) {
      // Construct `ans` on demand.
      if (++count[num] > ans.size())
        ans.push_back({});
      ans[count[num] - 1].push_back(num);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public List<List<Integer>> findMatrix(int[] nums) {
    // The number of rows we need equals the maximum frequency.
    List<List<Integer>> ans = new ArrayList<>();
    int[] count = new int[nums.length + 1];

    for (final int num : nums) {
      // Construct `ans` on demand.
      if (++count[num] > ans.size())
        ans.add(new ArrayList<>());
      ans.get(count[num] - 1).add(num);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def findMatrix(self, nums: List[int]) -> List[List[int]]:
    # The number of rows we need equals the maximum frequency.
    ans = []
    count = [0] * (len(nums) + 1)

    for num in nums:
      count[num] += 1
      # Construct `ans` on demand.
      if count[num] > len(ans):
        ans.append([])
      ans[count[num] - 1].append(num)

    return ans