# 可以排序法,二分查找法,优先队列, quick select
def find_Kth_smallest_number(nums, k):
heap = []
for num in nums:
if len(heap) < k:
heappush(heap, -num)
else:
if -num > heap[0]:
heappop(heap)
heappush(heap, -num)
return -heap[0]
def find_Kth_smallest_number(nums, k):
maxHeap = []
# put first k numbers in the max heap
for i in range(k):
heappush(maxHeap, -nums[i])
# go through the remaining numbers of the array, if the number from the array is smaller than the
# top(biggest) number of the heap, remove the top number from heap and add the number from array
for i in range(k, len(nums)):
if -nums[i] > maxHeap[0]:
heappop(maxHeap)
heappush(maxHeap, -nums[i])
# the root of the heap has the Kth smallest number
return -maxHeap[0]
手写heappush
Heaps are arrays for which heap[k] <= heap[2k+1] and heap[k] <= heap[2k+2] for all k
# 其他: 1382. Balance a Binary Search Tree
def heappush(heap, item):
# 将新元素添加到列表末尾
heap.append(item)
# 获取新元素的索引
i = len(heap) - 1
# 向上迭代调整堆
while i > 0:
parent = (i - 1) // 2
# 如果新元素比其父节点小,则交换它们的位置
if heap[i] < heap[parent]:
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
else:
break
# 示例
heap = [3, 8, 10, 11, 9, 20]
print("原始堆:", heap)
heappush(heap, 5)
print("添加元素后的堆:", heap)