python模块之heapq

##heapq简单介绍

堆特征:堆列表位置i处的元素总是大于位置i // 2处的元素(反过来说就是小于位置2 * i 和 2 * i + 1处的元素)

##api介绍

---

heapify(list) 让列表具有堆特征

heappush(heap, item) 将值压入堆中

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

heapreplace(heap, item) 弹出最小的元素,并将值压入堆中

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

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

heappushpop(heap, item) 将item压入堆中然后弹出最小的元素

merge(*iterables, key=None, reverse=False) 将有序序列进行合并排序,返回生成器序列

---

##贪心算法使用

![](https://upload-images.jianshu.io/upload_images/16683360-bac07541a1a4dfff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

```python

import collections

import heapq

def reorganizeString(S):

c = collections.Counter(S).items()

m = max(c, key=lambda x: x[1])[1]

if m > (len(S) + 1) // 2:

return ""

if len(S) < 3:

print(S)

res = []

x = [(-x[1], x[0]) for x in c]

heapq.heapify(x)

while len(x) > 1:

c1, top1 = heapq.heappop(x)

c2, top2 = heapq.heappop(x)

res.extend([top1, top2])

if c1 < -1:

heapq.heappush(x, ((c1 + 1), top1))

if c2 < -1:

heapq.heappush(x, ((c2 + 1), top2))

if x:

res.append(x[0][1])

return ''.join(res)

if __name__ == '__main__':

print(reorganizeString('aab'))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值