ORIGIN

LeetCode 1046. Last Stone Weight

ACM 1 min87 words

Problem Description

1046. Last Stone Weight

Description

Do as the game. Choose two heaviest stone and do the subtraction.

Use Priority Queue to easily find the two heaviest stone.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> pq(stones.begin(), stones.end());
while(pq.size() > 1) {
int x = pq.top();
pq.pop();
int y = pq.top();
pq.pop();
if(x != y) {
pq.push(x - y);
}
}
if(pq.empty()) return 0;
return pq.top();
}
};
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|