题解 | #牛群的第 m大的和#
牛群的第 m大的和
https://www.nowcoder.com/practice/04257790a4314942b26df19df9f68581
题目描述有bug,这里求得是第m大,而题中一直说的是第m小
key:
- 将堆中的每个数都拿出来与新的num相加最后放入新的堆中,实现大小比较
- 题目只需要求最后往前数第m个数就行,所以前面的结果都可以舍弃
class Solution:
def mthSmallestSum(self , nums: List[int], m: int) -> int:
heap1 = [0]
for i in range(len(nums)):
heap2 = []
# 将堆中的每个数都拿出来与新的num相加最后放入新的堆中,实现大小比较
while heap1:
top_num = heapq.heappop(heap1)
heapq.heappush(heap2, top_num)
heapq.heappush(heap2, top_num + nums[i])
# 题目只需要求最后往前数第m个数就行,所以前面的结果都可以舍弃
while len(heap2) > m:
heapq.heappop(heap2)
heap1 = heap2
return heap1[0]
查看11道真题和解析