力扣 347. 前K个高频元素

解法: 堆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def topKFrequent(nums, k):
def heap_up(i):
cur, parent = i, (i - 1) >> 1
while cur > 0 and heap[cur][1] >= heap[parent][1]:
heap[cur], heap[parent] = heap[parent], heap[cur]
heap_down(cur)
cur = parent
parent = (cur - 1) >> 1

def heap_down(i):
cur, left, right = i, 2 * i + 1, 2 * i + 2
while left < heap_num :
x, nex = heap[cur][1], cur
if left < heap_num and x < heap[left][1]:
nex = left
x = heap[left][1]
if right < heap_num and x < heap[right][1]:
nex = right
if cur != nex:
heap[cur], heap[nex] = heap[nex], heap[cur]
cur = nex
left, right = 2 * cur + 1, 2 * cur + 2
else:
break


# 堆排序
heap = []
heap_num = 0
for num in nums:
i = 0
while i < heap_num and heap[i][0] != num: i += 1
if i >= heap_num:
heap.append([num, 1])
heap_num += 1
else:
heap[i][1] += 1
# 上浮堆元素
heap_up(i)
# print(heap)
# 输出结果
ret = []
for i in range(k):
ret.append(heap[0][0])
heap[0], heap[-1] = heap[-1], heap[0]
heap.pop()
heap_num -= 1
heap_down(0)
# print(ret[-1], heap)
# print(ret)
return ret
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信