2019-09-17 LC 692 Top K Frequent Elements

Description

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Solution

  1. dict + sort
    Time O(NlogN)
    Space O(N)
  2. count + priority queue/ heap
    Time O(NlogK)
    Space O(N)
  3. Bucket sorting
    Time O(N)
    Space:
    Array O(N) Hash
    table O(N)
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        res = []
        count_dict = {}
        max_freq = 0
        bucket = {}
        # count max freq for hash table
        for n in nums:
            count_dict[n]=count_dict.get(n,0)+1
            if max_freq < count_dict[n]:
                max_freq = count_dict[n]
        # build bucket
        for n in count_dict.keys(): 
            if bucket.has_key(count_dict[n]):
                 bucket[count_dict[n]].append(n)
            else:
                 bucket[count_dict[n]] = [n]
      # select top K
        for i in range(max_freq,-1,-1):
            if bucket.has_key(i):
                for val in bucket[i]:
                    if len(res) < k:
                        res.append(val)
                    
        return res
    ```                
                    
            
        
                
        

你可能感兴趣的:(2019-09-17 LC 692 Top K Frequent Elements)