Given a non-empty array of integers, return the k most frequent elements.
Example:
Given [1,1,1,2,2,3] and k = 2, return [1,2].
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个频率最高的元素。
链接:LeetCode:https://leetcode.com/problems/top-k-frequent-elements/description/
使用哈希表(python 中字典)来存储各个元素出现的次数,键(key)为对应元素,值(value)为对应元素出现个数。再对该哈希表(字典)按照值进行排序。
代码(python):
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
Dict = {}
for i in range(len(nums)):
if nums[i] in Dict:
Dict[nums[i]] = Dict[nums[i]] + 1
else:
Dict[nums[i]] = 1
output = sorted(Dict.items(), key=lambda e: e[1], reverse=True)
final = []
for i in range(k):
final.append(output[i][0])
return final
solution = Solution()
output = solution.topKFrequent([1,1,1,2,2,3],2)
print(output)
sort 与 sorted 区别:
语法
>>>a = [5,7,6,3,4,1,2]
>>> b = sorted(a) # 保留原列表
>>> a
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]
>>> L=[('b',2),('a',1),('c',3),('d',4)]
>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) # 利用cmp函数
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> sorted(L, key=lambda x:x[1]) # 利用key
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2]) # 按年龄排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(students, key=lambda s: s[2], reverse=True) # 按降序
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>>