1046. Last Stone Weight

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

We have a collection of rocks, each rock has a positive integer weight.

Each turn, we choose the two heaviest rocks 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

題目翻譯:

我們有一個岩石集合,每個岩石都有一個正整數權重。 每轉一圈,我們選擇兩塊最重的岩石並將它們粉碎在一起。 假設寶石的權重為 x 和 y,x <= y。 這次粉碎的結果是:

如果 x == y,兩塊石頭都被徹底摧毀;
如果 x!= y,重量 x 的石頭被完全破壞,重量 y 的石頭具有新的重量 y-x。 最後,剩下最多 1 塊石頭。 返回這塊石頭的重量(如果沒有留下石塊,則返回 0)

程式思路:
每次從 vector 取出兩個最大的數字,將其碰撞留下較大的,將其塞回去

class Solution
{
public:
    int lastStoneWeight(vector<int>& stones)
    {
        while(stones.size() > 0)
        {
            //Find the first weight stone.
            auto it1 = max_element(std::begin(stones), std::end(stones));
            int stone1 = *it1;

            //Find the second weight stone.
            *it1 = 0;
            auto it2 = max_element(std::begin(stones), std::end(stones));

            if(*it2 == 0)
                return stone1;

            //Smash stones
            *it1 = stone1 - *it2;
            *it2 = 0;
        }
        return 0;
    }
};

  轉載請註明: YuYan's blog 1046. Last Stone Weight

  目錄