2024-01-02 Daily Challenge

Today I have done leetcode's January LeetCoding Challenge with cpp.

January LeetCoding Challenge 2

Description

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.

 

Example 1:

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
- 1
All 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.

Example 2:

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.

 

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= nums.length

Solution

auto speedup = [](){
  cin.tie(nullptr);
  cout.tie(nullptr);
  ios::sync_with_stdio(false);
  return 0;
}();
class Solution {
public:
  vector<vector<int>> findMatrix(vector<int>& nums) {
    map<int, int> count;
    int sz = 0;
    for(auto n : nums) {
      count[n] += 1;
      sz = max(sz, count[n]);
    }
    vector<vector<int>> answer(sz);
    for(const auto &[n, c] : count) {
      for(int i = 0; i < c; ++i) {
        answer[i].push_back(n);
      }
    }
    return answer;
  }
};

// Accepted
// 1035/1035 cases passed (29 ms)
// Your runtime beats 5.35 % of cpp submissions
// Your memory usage beats 70.96 % of cpp submissions (29.9 MB)