from heapq import heapreplace, heappush defmin_heap(self, nums: List[int], k: int) -> List[int]: res = [] for i in range(len(nums)): if i < k: heappush(res, nums[i]) elif nums[i] > res[0]: heapreplace(res, nums[i])
return res
max heap的话,入堆的数转负数,跟堆顶比较的大于号不变,出堆后转为整数 注意第6行res[0]并没有负号,因为res已经是负数
1 2 3 4 5 6 7 8 9
defmax_heap(self, nums: List[int], k: int) -> List[int]: res = [] for i in range(len(nums)): if i < k: heappush(res, -nums[i]) elif -nums[i] > res[0]: heapreplace(res, -nums[i]) res = [-n for n in res] return res
BFS + Heap
1 2 3 4 5 6 7 8 9 10 11 12 13 14
defbfs(self, nums, start, k) -> List[int]: heap, res = ([start])), [] visited.add(start) while heap: node = heapq.heappop(heap) res.append(node) if len(res) == k: break for neighbor in graph[node]: if neighbor in visited: continue heap.append(neighbor) visited.add(neighbor) return res