mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:22:55 +08:00
Merge pull request #2464 from OrangeLiuSSE/patch-1
Update 0347.前K个高频元素.md
This commit is contained in:
@ -218,7 +218,7 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Python:
|
### Python:
|
||||||
|
解法一:
|
||||||
```python
|
```python
|
||||||
#时间复杂度:O(nlogk)
|
#时间复杂度:O(nlogk)
|
||||||
#空间复杂度:O(n)
|
#空间复杂度:O(n)
|
||||||
@ -246,6 +246,31 @@ class Solution:
|
|||||||
result[i] = heapq.heappop(pri_que)[1]
|
result[i] = heapq.heappop(pri_que)[1]
|
||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
|
解法二:
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
|
||||||
|
# 使用字典统计数字出现次数
|
||||||
|
time_dict = defaultdict(int)
|
||||||
|
for num in nums:
|
||||||
|
time_dict[num] += 1
|
||||||
|
# 更改字典,key为出现次数,value为相应的数字的集合
|
||||||
|
index_dict = defaultdict(list)
|
||||||
|
for key in time_dict:
|
||||||
|
index_dict[time_dict[key]].append(key)
|
||||||
|
# 排序
|
||||||
|
key = list(index_dict.keys())
|
||||||
|
key.sort()
|
||||||
|
result = []
|
||||||
|
cnt = 0
|
||||||
|
# 获取前k项
|
||||||
|
while key and cnt != k:
|
||||||
|
result += index_dict[key[-1]]
|
||||||
|
cnt += len(index_dict[key[-1]])
|
||||||
|
key.pop()
|
||||||
|
|
||||||
|
return result[0: k]
|
||||||
|
```
|
||||||
|
|
||||||
### Go:
|
### Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user