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();    

}

};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章