标签:http pre python3 数字 break href name 第k小 链表
用堆排序找出list中第K小的数字, 用小顶堆
def min_heap_k(nums, topk):
def siftdown(nums, e, begin, end):
i = begin
j = 2*i + 1
while j < end:
if j+1 < end and num[j+1] < nums[j]:
j += 1
if e < nums[j]:
break
nums[i] = nums[j]
i = j
j = 2*i + 1
nums[i] = e
end = len(nums)
for k in range(end//2, -1, -1):
siftdown(nums, e, k, end)
for k in range(end-1, 0, -1):
e = nums[k]
topk -= 1
if topk == 0:
return nums[0]
siftdown(nums, e, 0, k)
if __name__ == "__main__":
print(min_heap_k([2, 3, 1, 5, -1, 0, -10, -9, -6], topk=4))
标签:http pre python3 数字 break href name 第k小 链表
原文地址:https://www.cnblogs.com/theodoric008/p/8981846.html