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

은엽·2024년 1월 2일

문제풀이

목록 보기
27/33

Problem

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차원 배열로 변환하는 문제이다. 2차원 배열의 조건은 각 배열에 동일한 수가 포함되면 안된다는 것이다.

Solution

  • 먼저 1차원 배열에 포함된 숫자와 숫자의 개수를 구해 딕셔너리에 저장한다.
  • 최대 개수를 기준으로 빈 2차원 리스트를 생성한다.
  • key를 기준으로 딕셔너리를 탐색해서 숫자의 개수 n개의 배열에 숫자 key를 추가한다.
  • 생성한 2차원 리스트를 반환한다.

Python Code

from collections import defaultdict

class Solution:
    def findMatrix(self, nums: List[int]) -> List[List[int]]:
        num_count = defaultdict(int)
        for num in nums:
            num_count[num] += 1
        max_count = max(num_count.values())
        result = [[] for _ in range(max_count)]
        for key in num_count.keys():
            for i in range(num_count[key]):
                result[i].append(key)
        return result
profile
어떻게 했더라

0개의 댓글