# 可以排序法,二分查找法,优先队列, quick selectdeffind_Kth_smallest_number(nums,k): heap = []for num in nums:iflen(heap)< k:heappush(heap, -num)else:if-num > heap[0]:heappop(heap)heappush(heap, -num)return-heap[0]
deffind_Kth_smallest_number(nums,k): maxHeap = []# put first k numbers in the max heapfor i inrange(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 arrayfor i inrange(k, len(nums)):if-nums[i]> maxHeap[0]:heappop(maxHeap)heappush(maxHeap, -nums[i])# the root of the heap has the Kth smallest numberreturn-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 Treedefheappush(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 = parentelse:break# 示例heap = [3,8,10,11,9,20]print("原始堆:", heap)heappush(heap, 5)print("添加元素后的堆:", heap)