LeetCode 1046. Last Stone Weight

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int lastStoneWeight(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
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> b - a);
for (int stone : stones)
q.offer(stone);
while (q.size() > 1) {
int y = q.poll();
int x = 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
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
q = [-stone for stone in stones]
heapq.heapify(q)
while len(q) > 1:
y, x = heapq.heappop(q), heapq.heappop(q)
if x != y:
heapq.heappush(q, y - x)
if q: return -q[0]
return 0