Skip to content

Commit 810a8da

Browse files
author
weiy
committed
Top K Frequent Elements
1 parent e344125 commit 810a8da

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: Array/TopKFrequentElements.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Given a non-empty array of integers, return the k most frequent elements.
3+
4+
Example 1:
5+
6+
Input: nums = [1,1,1,2,2,3], k = 2
7+
Output: [1,2]
8+
Example 2:
9+
10+
Input: nums = [1], k = 1
11+
Output: [1]
12+
Note:
13+
14+
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
15+
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
16+
17+
思路:
18+
首先是计算出每个数字出现的频率,之后排序频率,输出最高的k位。
19+
20+
字典(哈希表),sorted(排序)。
21+
22+
beat 88%
23+
24+
测试用例:
25+
https://leetcode.com/problems/top-k-frequent-elements/description/
26+
27+
"""
28+
class Solution(object):
29+
def topKFrequent(self, nums, k):
30+
"""
31+
:type nums: List[int]
32+
:type k: int
33+
:rtype: List[int]
34+
"""
35+
36+
nums_dict = {}
37+
38+
for i in nums:
39+
try:
40+
nums_dict[i] += 1
41+
except KeyError:
42+
nums_dict[i] = 1
43+
44+
return sorted(nums_dict, key=lambda x: nums_dict[x], reverse=True)[:k]

0 commit comments

Comments
 (0)