You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions:
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차원 배열의 조건은 각 배열에 동일한 수가 포함되면 안된다는 것이다.
key를 기준으로 딕셔너리를 탐색해서 숫자의 개수 n개의 배열에 숫자 key를 추가한다.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