Created
May 13, 2019 12:49
-
-
Save panyan928/163b68f6b3eb9a46026b362d79151096 to your computer and use it in GitHub Desktop.
最小堆排序找topK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 构建小顶堆跳转 | |
def sift(li, low, higt): | |
tmp = li[low] | |
i = low | |
j = 2 * i + 1 | |
while j <= higt: # 情况2:i已经是最后一层 | |
if j + 1 <= higt and li[j + 1] < li[j]: # 右孩子存在并且小于左孩子 | |
j += 1 | |
if tmp > li[j]: | |
li[i] = li[j] | |
i = j | |
j = 2 * i + 1 | |
else: | |
break # 情况1:j位置比tmp小 | |
li[i] = tmp | |
def top_k(li, k): | |
heap = li[0:k] | |
# 建堆 | |
for i in range(k // 2 - 1, -1, -1): | |
sift(heap, i, k - 1) | |
for i in range(k, len(li)): | |
if li[i] > heap[0]: | |
heap[0] = li[i] | |
sift(heap, 0, k - 1) | |
# 挨个输出 | |
for i in range(k - 1, -1, -1): | |
heap[0], heap[i] = heap[i], heap[0] | |
sift(heap, 0, i - 1) | |
return heap | |
li = [0, 8, 6, 2, 4, 9, 1, 4, 6] | |
print(top_k(li, 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment