10/22/2021

[LeetCode] 1636. Sort Array by Increasing Frequency

 Problem : https://leetcode.com/problems/sort-array-by-increasing-frequency/

This is a bucket sort problem. Firstly put numbers with same frequency into same bucket. Then reverse sort numbers in the same bucket.


class Solution:
    def frequencySort(self, nums: List[int]) -> List[int]:
        bucket = defaultdict(list)
        
        for n, c in Counter(nums).items():
            bucket[c].append(n) 
            
        result = []
        
        for c in range(101):
            for n in sorted(bucket[c], reverse=True): 
                result += [n] * c
        
        return result

No comments:

Post a Comment