問題描述
Given a non-empty array of integers, return the k most frequent elements.
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個最常見的元素。
注意:
你可以假設k總是有效的,1≤k≤元素的個數。
你的算法的時間複雜度必須優於O(n log n),其中n是數組的大小。
例子1:
輸入: nums = [1,1,1,2,2,3], k = 2
輸出: [1,2]
例子2:
輸入: nums = [1], k = 1
輸出: [1]
Python 實現
實現一
最直接的解決思路,使用 dict 或者 map 統計元素出現的頻率,然後選出出現頻率最高的 K 個元素。
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if k == len(nums):
return nums
# Count the frequency with dictionary (key-value pair).
dic = {}
for num in nums:
dic[num] = dic.get(num, 0) + 1
# Sort in ascending order; compare frequency first, then compare the elements itself; reverse into descending order.
sorted_list_pair = sorted(dic.items(), key=lambda kv:(kv[1], kv[0]), reverse=True)
l = [element[0] for element in sorted_list_pair]
return l[:k]
實現二:堆
題目要求算法的時間複雜度必須優於O(n log n),出現 lon n 其實就提示了可以通過類似樹這樣的二分數據結構求解。在這裏我們可以用元素的出現的頻率作爲 key 來構建堆,然後取出最大的 K 的結點即可。(這裏直接使用 python 的庫實現)
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
# Method 2: heap.
count = collections.Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)