尾部插入
头部弹出
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
if k == 0:
return []
# python 中存储的是小顶堆 进行取负值操作
arr = [-num for num in arr]
heap = arr[:k]
heapq.heapify(heap) # 将list 转换为heap
for num in arr[k:]:
if num > heap[0]: # 选后面负数进行 大小的比较 大的入堆
heapq.heapreplace(heap, num)
return [-num for num in heap] # 遍历堆, 取反 返回最小的K个数
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones = [-stone for stone in stones]
heapq.heapify(stones)
while len(stones) > 1:
x = stones[0]
heapq.heappop(stones) # heappop 弹出 heapq第一个值
y = stones[0]
heapq.heappop(stones) # heappop 弹出 heapq第一个值
if x - y != 0:
heapq.heappush(stones,x -y)
if len(stones) == 0:
return 0
return -stones[0]
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
if k > len(nums):
self.heap = nums
heapq.heapify(self.heap)
else:
self.heap = nums[:k]
heapq.heapify(self.heap)
for num in nums[k:]:
if num > self.heap[0]:
heapq.heapreplace(self.heap, num)
def add(self, val: int) -> int:
if self.k > len(self.heap):
heapq.heappush(self.heap, val)
elif val > self.heap[0]:
heapq.heapreplace(self.heap,val)
return self.heap[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
目前出现的问题就是超时
num_tuple = [(u, v) for u in nums1 for v in nums2]
return heapq.nsmallest(k, num_tuple, key=lambda s: s[0] + s[1])
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = nums[:k]
heapq.heapify(heap)
for num in nums[k:]:
if num > heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, num)
return heap[0]