[LeetCode] Convert an Array Into a 2D Array With Conditions

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

You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions:

  • The 2D array should contain only the elements of the array nums.
  • Each row in the 2D array contains distinct integers.
  • The number of rows in the 2D array should be minimal.

Return the resulting array. If there are multiple answers, return any of them.

Note that the 2D array can have a different number of elements on each row.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<vector<int>> findMatrix(vector<int>& nums) {
unordered_map<int, int> mp;
vector<vector<int>> res;
for(int i = 0; i < nums.size(); i++) {
int idx = mp[nums[i]];
if(res.size() == idx) res.emplace_back();
res[idx].push_back(nums[i]);
mp[nums[i]] += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/02/PS/LeetCode/convert-an-array-into-a-2d-array-with-conditions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.