heapify
算法的递归Python3实现
Python3实现的heapify
算法(用于将一个数组转化为小根堆)
def heapify(arr, n, i):
smallest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] > arr[l]:
smallest = l
if r < n and arr[smallest] > arr[r]:
smallest = r
if smallest != i:
arr[i],arr[smallest] = arr[smallest],arr[i]
heapify(arr, n, smallest)
Note: 如果要用于将一个数组转化为大根堆,只需要修改
if l < n and arr[i] < arr[l]:
if r < n and arr[largest] < arr[r]:
将一个数组转化为小顶堆的实现就是:
for i in reversed(range(n // 2)):
heapify(heap1, n, i)
[monica]
[https://www.cnblogs.com/charles101/p/14055491.html]
应用:取数组最大的第k个数
根据上面递归算法实现
import heapq
class Solution:
def heapify(self, l):
# 维护一个小顶堆
lenl = len(l)
def heapify1(curi):
smallesti = curi
lefti = 2 * curi + 1
righti = 2 * curi + 2
if lefti < lenl and l[lefti] < l[smallesti]:
smallesti = lefti
if righti < lenl and l[righti] < l[smallesti]:
smallesti = righti
if smallesti != curi:
l[curi], l[smallesti] = l[smallesti], l[curi]
heapify1(smallesti)
for curi in reversed(range(lenl // 2)):
heapify1(curi)
def heappushpop(self, heap0, x):
# 替换小顶堆顶部再维护
heap0[0] = x
self.heapify(heap0)
def findKthLargest(self, nums: list[int], k: int) -> int:
# 选出l最大的第k个
heap0 = nums[:k]
self.heapify(heap0)
# print(heap0)
for li in nums[k:]:
if li > heap0[0]:
self.heappushpop(heap0, li)
return heap0[0]
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6]
k = 4
print(Solution().findKthLargest(nums, k)) # 4
递归的会超时
python库非递归heapify算法实现
import heapq
class Solution:
def findKthLargest(self, nums: list[int], k: int) -> int:
heap0 = nums[:k]
heapq.heapify(heap0)
for i in nums[k:]:
if i > heap0[0]:
heapq.heappushpop(heap0, i)
return heap0[0]
l = [3, 9, 5, 1, 7, 13, 6, 8]
k = 5
print(Solution().findKthLargest(l, k))
from:https://blog.csdn.net/pipisorry/article/details/131057941
ref: