Skip to content

Commit 37615a2

Browse files
authored
Create 0347 Top K Frequent Elements.md
1 parent 9695c78 commit 37615a2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

heap/0347 Top K Frequent Elements.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# 347. Top K Frequent Elements
2+
https://leetcode-cn.com/problems/top-k-frequent-elements/
3+
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
4+
5+
Example 1:
6+
Input: nums = [1,1,1,2,2,3], k = 2
7+
Output: [1,2]
8+
9+
Example 2:
10+
Input: nums = [1], k = 1
11+
Output: [1]
12+
13+
Constraints:
14+
1 <= nums.length <= 10^5
15+
k is in the range [1, the number of unique elements in the array].
16+
It is guaranteed that the answer is unique.
17+
18+
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
19+
20+
``` python3
21+
class Solution:
22+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
23+
fre=collections.Counter(nums)
24+
fre=sorted(fre.items(),key=lambda x:x[1],reverse=True)
25+
ans=[]
26+
for i in range(k):
27+
ans.append(fre[i][0])
28+
return ans
29+
```

0 commit comments

Comments
 (0)