classSolution { public: intlastStoneWeight(vector<int>& stones){ priority_queue<int> q; for (int s : stones) q.push(s); while (q.size() > 1) { int y = q.top(); q.pop(); int x = q.top(); q.pop(); if (y > x) q.push(y - x); } return q.empty() ? 0 : q.top(); } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { publicintlastStoneWeight(int[] stones) { PriorityQueue<Integer> q = newPriorityQueue<>((a, b) -> b - a); for (int stone : stones) q.offer(stone); while (q.size() > 1) { inty= q.poll(); intx= q.poll(); if (y > x) { q.offer(y - x); } } return q.isEmpty() ? 0 : q.poll(); } }
1 2 3 4 5 6 7 8 9 10
classSolution: deflastStoneWeight(self, stones: List[int]) -> int: q = [-stone for stone in stones] heapq.heapify(q) whilelen(q) > 1: y, x = heapq.heappop(q), heapq.heappop(q) if x != y: heapq.heappush(q, y - x) if q: return -q[0] return0