leetcode 1046. The weight of the last stone

leetcode 1046. The weight of the last stone

Question stem

There is a pile of stones, and the weight of each stone is a positive integer.
Each round, choose the two heaviest stones from them, and then smash them together. Suppose the weight of the stone is x and y, and x <= y. Then the possible results of crushing are as follows:
if x == y, then both stones will be completely crushed;
if x != y, then the stone of weight x will be completely crushed, and the new weight of the stone of weight y is yx.
In the end, at most only one stone will remain. Returns the weight of this stone. If there are no stones left, return 0.

Example:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
First select 7 and 8 to get 1, so the array is converted to [2,4,1,1,1],
then select If you get 2 and 4, you get 2, so the array is converted to [2,1,1,1], and
then 2 and 1, you get 1, so the array is converted to [1,1,1], and
finally 1 and 1 are selected. Get 0, the final array is converted to [1], which is the weight of the last remaining stone.

提示:
1 <= stones.length <= 30
1 <= stones[i] <= 1000

answer

The simplest and crudest way of thinking is to simulate directly, continuously sort the stones array in ascending order, take out the last two digits for comparison and then process until the number of elements in the stones array is less than or equal to 1.

class Solution {
    
    
public:
    int lastStoneWeight(vector<int>& stones) {
    
    
        while(stones.size() > 1){
    
    
            sort(stones.begin(),stones.end());
            int first = stones.back();
            stones.pop_back();
            int second = stones.back();
            stones.pop_back();
            if(first == second){
    
    
                continue;
            }else{
    
    
                stones.push_back(first - second);
            }
        }
        return stones.size() == 1 ? stones[0] : 0;
    }
};

The manual sorting part can also be replaced by priority_queue, the top element of the heap must be the largest by default

class Solution {
    
    
public:
    int lastStoneWeight(vector<int>& stones) {
    
    
        priority_queue<int> bigTopStones;
        for(auto i : stones){
    
    
            bigTopStones.push(i);
        }
        //堆顶元素一定是坠大的
        while(bigTopStones.size() > 1){
    
    
            int first = bigTopStones.top();
            bigTopStones.pop();
            int second = bigTopStones.top();
            bigTopStones.pop();
            if(first == second){
    
    
                continue;
            }else{
    
    
                bigTopStones.push(first - second);
            }
        }
        return bigTopStones.size() == 1 ? bigTopStones.top() : 0;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43662405/article/details/111992513