본문 바로가기
코딩테스트

C++ ] leetCode 2610 - Convert an Array Into a 2D Array With Conditions

by eteo 2023. 4. 9.

 

 

 

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

 

 

 

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    vector<vector<int>> findMatrix(vector<int>& nums) {
        vector<vector<int>> answer;        
        sort(nums.begin(), nums.end());
        int row = 0;
        while(!nums.empty())
        {
            answer.push_back(vector<int>());

            for(auto it = nums.begin(); it != nums.end(); )
            {
                if(answer[row].empty() || answer[row].back() != *it)
                {
                    answer[row].push_back(*it);
                    nums.erase(it);
                }
                else it++;
            }
            row++;
        }
        
        return answer;
    }
};

 

먼저 algorithm 헤더의 sort() 함수로 정렬하고, 중복을 피해 nums 벡터에서 원소를 빼서 answer 2차원 벡터에 넣는다. 처엔 num.size() 를 구해서 반복하고 index로 접근했는데, iterator를 사용해 nums.end()까지 반복하고 * 역참조해서 요소에 접근하는 편이 효율적일 것 같아서 바꿨다. iterator는 쓸수록 편하고 좋은것 같다.

 

 

 

검증용 코드

int main() {
    Solution solution;
    vector<int> nums = {1, 3, 4, 1, 2, 3, 1};
    vector<vector<int>> answer = solution.findMatrix(nums);

    for(int i = 0; i < answer.size(); i++) {
        for(int j = 0; j < answer[i].size(); j++) {
            cout << answer[i][j];
            if(j!=answer[i].size()-1) cout<<',';
        }
        cout << endl;
    }

    return 0;
}