Algorithm/NeetCode

Convert an Array Into a 2D Array With Conditions

Tony Lim 2024. 11. 22. 09:42
728x90

https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/

 

class Solution:
    def findMatrix(self, nums: List[int]) -> List[List[int]]:
        count = defaultdict(int)
        res = []
        for n in nums:
            row = count[n]
            if len(res) == row:
                res.append([])
                
            res[row].append(n)
            count[n] += 1
        return res

since we don't want any duplicate when creating parital array.

we count the occurence of number. when it becomes more than 1

we create another partital array and append number there

728x90