1046. Last Stone Weight

这里就是用大顶堆。priority_queue 

堆的定义:https://blog.csdn.net/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();    

}

};

发布了57 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/declanzane/article/details/104203527