这里就是用大顶堆。priority_queue
堆的定义:https://blog.youkuaiyun.com/lym940928/article/details/89635690
//构造一个空的优先队列,此优先队列是一个小顶堆 priority_queue<int,vector<int>,greater<int> > small_heap;
时间复杂度时o(n) + nlogn.
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> big_heap;
for(auto stone:stones) big_heap.push(stone);
int top1(0), top2(0);
while(big_heap.size() >= 2) {
top1 = big_heap.top();
big_heap.pop();
top2 = big_heap.top();
big_heap.pop();
if(top1 != top2) big_heap.push(abs(top1-top2));
}
return big_heap.size() == 0?0:big_heap.top();
}
};