[LeetCode] 1046. Last Stone Weight 最后的石頭重量



We have a collection of stones, each stone has a positive integer weight.

Each turn, we choose the two heaviest stones and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is:

  • If x == y, both stones are totally destroyed;
  • If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

At the end, there is at most 1 stone left.  Return the weight of this stone (or 0 if there are no stones left.)

Example 1:

Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.

Note:

  1. 1 <= stones.length <= 30
  2. 1 <= stones[i] <= 1000

這道題說是給了一堆重量不同的石頭,每次選出兩個最重的出來相互碰撞,若二者重量相同,則直接湮滅了,啥也不剩,否則剩一個重量為二者差值的石頭。然后繼續如此操作,直至啥也不剩(返回0),或者剩下一個石頭(返回該石頭的重量)。這道題是一道 Easy 的題目,沒有太大的難度,主要就是每次要選出最大的兩個數字,若是給數組排序,是可以知道最后兩個數字是最大的,然是碰撞過后若有剩余,要將這個剩余的石頭加到數組的合適位置,每次都排一次序顯然時間復雜度太大。這里需要用一個更合理的數據結構,最大堆,在 C++ 中用優先隊列實現的,每次加入一個新的石頭,就會自動根據其重量加入到正確的位置。起始時將所有的石頭加入優先隊列中,然后進行循環,條件是隊列中的石頭個數大於1,然后取出隊首兩個石頭,假如重量不等,則將差值加入隊列。最終只需要判斷隊列是否為空,是的話返回0,否則返回隊首元素,參見代碼如下:


class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
        priority_queue<int> q;
        for (int stone : stones) q.push(stone);
        while (q.size() > 1) {
            int first = q.top(); q.pop();
            int second = q.top(); q.pop();
            if (first > second) q.push(first - second);
        }
        return q.empty() ? 0 : q.top();
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1046


參考資料:

https://leetcode.com/problems/last-stone-weight/

https://leetcode.com/problems/last-stone-weight/discuss/294956/JavaC%2B%2BPython-Priority-Queue


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM