题目描述:
有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为
x
和y
,且x <= y
。那么粉碎的可能结果如下:
- 如果
x == y
,那么两块石头都会被完全粉碎;- 如果
x != y
,那么重量为x
的石头将会完全粉碎,而重量为y
的石头新重量为y-x
。最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回
0
。提示:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
算法:
使用堆排序进行模拟
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
if(stones.size() == 0)
return 0;
priority_queue<int, vector<int>, less<int> > pq;
for(auto& stone: stones)
pq.push(stone);
while(pq.size()>1)
{
int first = pq.top();
pq.pop();
int second = pq.top();
pq.pop();
if(first == second)
continue;
else
pq.push(first - second);
}
if(pq.size()==1)
return pq.top();
return 0;
}
};