anspython_python堆(heapq)的实现

堆的实现

最小的K个数。

堆插入、取出都是log(n)的复杂度。

class Heap:

def __init__(self):

self.data_list = []

def insert(self, x):

# 先把元素放在最后,然后从后往前依次堆化

# 这里以大顶堆为例,如果插入元素比父节点大,则交换,直到最后

self.data_list.append(x)

index = len(self.data_list) - 1

while index > 0:

p_index = index >> 1

if self.data_list[index] < self.data_list[p_index]:

self.data_list[index], self.data_list[p_index] = self.data_list[p_index], self.data_list[index]

index = p_index

def top(self):

return self.data_list[0]

def pop(self):

# 删除堆顶元素,然后将最后一个元素放在堆顶,再从上往下依次堆化

remove_data = self.data_list[0]

self.data_list[0] = self.data_list[-1]

self.data_list.pop()

self.heapify(0)

return remove_data

def heapify(self, index):

max_index = len(self.data_list) - 1

while index <= max_index:

maxvalue_index = index

left_index, right_index = (index << 1),  (index << 1) + 1

if (left_index <= max_index) and (self.data_list[left_index] < self.data_list[maxvalue_index]):

maxvalue_index = left_index

if (right_index <= max_index) and (self.data_list[right_index] < self.data_list[maxvalue_index]):

maxvalue_index = right_index

if maxvalue_index == index:

break

self.data_list[maxvalue_index], self.data_list[index] = self.data_list[index], self.data_list[maxvalue_index]

index = maxvalue_index

class Solution(object):

def smallestK(self, arr, k):

"""

:type arr: List[int]

:type k: int

:rtype: List[int]

"""

heapq = Heap()

for a in arr:

heapq.insert(a)

# print(heapq.data_list)

ans = []

for _ in range(k):

ans.append(heapq.pop())

return ans

python内置堆heapq

heap是一个list,具有堆特性的heap不一定是排好序的,使用heapq.heappop()出来的结果才是排好序的。

python默认的heapq模块只支持最小堆的构建。最大堆构建时,值可以乘-1,结果也再返回去。

heapq方法用法

heapq.heappush(heap, x)将x压入堆heap中

heapq.heappop(heap)从堆heap中弹出最小的元素

heapq.heapify(heap)让列表heap具备堆特征

heapq.heapreplace(heap, x)弹出最小的元素,并将x压入堆heap中

heapq.nlargest(n, iterable, key=None)返回iter中n个最大的元素

heapq.nsmallest(n, iterable, key=None)返回iter中n个最小的元素

example

import heapq

# 1.创建堆

# 方法一

nums = [3, 2, 4, 8, 3, 1, 4, 9, 4]

my_heapq_1 = []

for num in nums:

heapq.heappush(my_heapq_1, num)  # 加入堆

# 方法二

my_heapq_2 = [3, 2, 4, 8, 3, 1, 4, 9, 4]

heapq.heapify(my_heapq_2)

# 2. 访问堆顶

print([heapq.heappop(my_heapq_1) for _ in range(len(my_heapq_1))])  # 堆排序结果

print([heapq.heappop(my_heapq_2) for _ in range(len(my_heapq_2))])

# [1, 2, 3, 3, 4, 4, 4, 8, 9]

# 3.访问堆顶并替换

heapq.heapreplace(my_heapq_1, 23)

print([heapq.heappop(my_heapq_1) for _ in range(len(my_heapq_1))])  # 堆排序结果

# [2, 3, 3, 4, 4, 4, 8, 9, 23]

# 4.最大n个/最小n个。

nlargest = heapq.nlargest(5, my_heapq_1)

nsmallest = heapq.nsmallest(5, my_heapq_1)

print(nlargest, nsmallest)

# [9, 8, 4, 4, 4] [1, 2, 3, 3, 4]

元组堆

import heapq

# 1.创建堆

my_heapq = []

heapq.heappush(my_heapq, (5, 7))

heapq.heappush(my_heapq, (5, 4))

heapq.heappush(my_heapq, (7, 2))

heapq.heappush(my_heapq, (1, 3))

heapq.heappush(my_heapq, (3, 1))

print([heapq.heappop(my_heapq) for _ in range(len(my_heapq))])

# 2.最大n个/最小n个。

nlargest = heapq.nlargest(5, my_heapq, key=lambda e: (e[0], e[1]))

nsmallest = heapq.nsmallest(5, my_heapq, key=lambda e: (e[1], e[0]))

print(nlargest, nsmallest)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值