import heapq classSolution: deflastStoneWeight(self, stones: List[int]) -> int: heap = [] for i in stones: heapq.heappush(heap, -i) whilelen(heap) > 1: a = heap[0] heapq.heappop(heap) b = heap[0] heapq.heappop(heap) if a > b: heapq.heappush(heap, b - a) elif a < b: heapq.heappush(heap, a - b) iflen(heap) == 0: return0 return -heap[0]
import heapq classSolution: defkClosest(self, points: List[List[int]], k: int) -> List[List[int]]: h = [] ans = [] for i in points: heapq.heappush(h, (i[0] * i[0] + i[1] * i[1], i)) for i inrange(k): ans.append(h[0][1]) heapq.heappop(h) return ans
import random classSolution: deffindKthLargest(self, nums: List[int], k: int) -> int: pivot = random.choice(nums) big = [x for x in nums if x > pivot] equal = [x for x in nums if x == pivot] small = [x for x in nums if x < pivot] iflen(big) >= k: returnself.findKthLargest(big, k) eliflen(big) + len(equal) >= k: return pivot else: returnself.findKthLargest(small, k - len(big) - len(equal))
import heapq from collections import Counter, deque classSolution: defleastInterval(self, tasks: List[str], n: int) -> int: count = Counter(tasks) heap = [-i for i in count.values()] heapq.heapify(heap) time = 0 q = deque() while heap or q: time += 1 if heap: cnt = heapq.heappop(heap) + 1 if cnt != 0: q.append((cnt, time + n)) if q and q[0][1] == time: heapq.heappush(heap, q.popleft()[0]) return time
或者, 考虑总时长是由最频繁的任务决定的, 例如 n=2, 最频繁的任务是 A, 则先排好 A:
A _ _ | A _ _ | A
若有多个和 A 一样频繁的任务, 会影响最后一组的大小, 其余直接放入空位中, 若空位放不下则任意安排都不会影响总时长. 所以可以直接算.