添加0347前K个高频元素 python3 版本

This commit is contained in:
boom-jumper
2021-06-01 18:08:16 +08:00
committed by GitHub
parent 7b3f8ea4dd
commit 3362183d84

View File

@ -162,6 +162,63 @@ class Solution {
Python Python
```python
class Solution:
def sift(self, alist, low, high):
'''小根堆构建'''
i = low
j = 2 * i + 1
tmp = alist[low]
while j <= high:
if j + 1 <= high and alist[j+1] <= alist[j]:
j += 1
if alist[j] < tmp:
alist[i] = alist[j]
i = j
j = 2 * i + 1
else:
alist[i] = tmp
break
else:
alist[i] = tmp
def topK(self, nums, k):
# 建立小根堆
heap = nums[:k]
for i in range((k-2)//2, -1, -1):
self.sift(heap, i, k-1)
# 把后续的k到len(nums)填充到小根堆里
for i in range(k, len(nums)):
if nums[i] >= heap[0]:
heap[0] = nums[i]
self.sift(heap, 0, k-1)
# 排序
for i in range(k-1, -1, -1):
heap[0], heap[i]= heap[i], heap[0]
self.sift(heap, 0, i-1)
return heap
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dict1 = dict()
for val in nums:
if val not in dict1:
dict1[val] = 1
else:
dict1[val] += 1
res = list()
ind = list()
for item in dict1:
res.append([dict1[item], item])
result = list()
heap = self.topK(res, k)
print(heap)
for val in heap:
result.append(val[1])
return result
```
Go Go