1. 程式人生 > >【python3】leetcode 347. Top K Frequent Elements(Medium)

【python3】leetcode 347. Top K Frequent Elements(Medium)

347. Top K Frequent Elements(Medium

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]

Example 2:

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

Note:

  • You may assume k is always valid, 1 ≤ k
     ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

求頻率最高的k個數字,時間複雜度要優於 O(n log n),

第一個想到先計算每個數字的頻率-》collections.Counter

然後根據頻率排序取最後k個的數字

做這道題卡在如何對字典排序,參考了《

(補充了一種直接使用count.most_common(n)

的方法,)count.most_common(n)返回list,對count按照計數排序返回數量最多的n個,返回的list的格式是[(key1 , val1 ) , (key2,val2),...,(keyn,valn)]

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count = collections.Counter(nums)
        k_freq = count.most_common(k)
        return [k[0] for k in k_freq]

下面兩種都是把dict先排序 

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count = collections.Counter(nums)
        l = [[val,key] for key,val in count.items()]
        l.sort()
        freq =  [v[1] for v in l]
        return freq[-k:]

還有一種利用sorted()裡的key引數根據dict的val排序,然後利用odereddict順序不變的特性直接取末k個key返回 

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count = collections.Counter(nums)
        freq = collections.OrderedDict(sorted(count.items(),key=lambda t:t[1])) #sort according to val
        freq = list(freq.keys())
        return freq[-k:]