从数量最多的堆取走礼物

从数量最多的堆取走礼物

1、题目

image-20231030225117425 ## 2、题解

思路:每轮都寻找最大值,可以最大堆模拟。循环\(k\)次,每次循环弹出堆顶\(top\),然后把\(\lfloor\sqrt{top}\rfloor\)入堆。

题解代码:

1
2
3
4
5
6
7
8
9
10
class Solution:
def pickGifts(self, gifts: List[int], k: int) -> int:
for i in range(len(gifts)):
gifts[i] *= -1
heapify(gifts)
print(gifts)
while k and -gifts[0]>1:
heapreplace(gifts,-isqrt(-gifts[0]))
k -= 1
return -sum(gifts)

我的方法(时间复杂度被爆杀):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def pickGifts(self, gifts: List[int], k: int) -> int:
while(k != 0):
temp=0
temp_num = gifts[0]
for i in range(len(gifts)):
if gifts[i]>temp_num:
temp_num = gifts[i]
temp = i

gifts[temp] = int(gifts[temp] **0.5)
k = k -1
sum_gifts = 0
for j in range(len(gifts)):
sum_gifts += gifts[j]
return sum_gifts

从数量最多的堆取走礼物
http://example.com/2023/10/30/min-gifts/
作者
Z Z
发布于
2023年10月30日
许可协议