SoFunction
Updated on 2025-03-04

Go Language LeetCode Question Solution 1046 The weight of the last stone

Question description

1046. The weight of the last stone - LeetCode

There are a bunch of stones, each of which is a positive integer.

Each round, select two pieces from themThe heaviestStones, then crush them together. Assume that the weight of the stone isxandy,andx <= y. Then the possible results of crushing are as follows:

  • If x == y, then both stones will be completely crushed;
  • If x != y, the stone with a weight of x will be completely crushed, while the stone with a weight of y is new weight of y-x.

Finally, at most one stone will be left. Returns the weight of this stone. If no stones are left, return 0.

Example:

Input: [2,7,4,1,8,1]
Output: 1
explain:
First select 7 and 8 to get 1, so the array is converted to [2,4,1,1,1],
Select 2 and 4 again to get 2, so the array is converted to [2,1,1,1],
Then there are 2 and 1, resulting in 1, so the array is converted to [1,1,1],
Finally, select 1 and 1, get 0, and the final array is converted to [1], which is the weight of the last stone left.

hint:

1 <= <= 30

1 <= stones[i] <= 1000

Idea Analysis

  • Sorting is used here, and an array from small to large is obtained.
  • Next, use the lastIndex pointer to point to the last element that has not been crushed, take the two largest stones, and subscribe lastIndex, lastIndex-1. Assign the difference between the two to lastIndex-1. Moving the lastIndex pointer is equivalent to deleting the last element.
  • It can also be rewritten to recursion, with the same idea.

AC Code

import ;
class Solution {
//A bunch of stones Each stone is an integer weight// Each round, select two stones with the largest weight x, y x<=y// x==y Completely crushed x!=y y=y-x// At most one stone will be left in the end. Return to the weight of the stone. If there is no left, return 0.    private int lastIndex;
    private int left;
    public int lastStoneWeight(int[] stones) {
        lastIndex = -1;
        (stones);
        while (lastIndex&gt;=1){
            left = stones[lastIndex]-stones[lastIndex-1];
            if (left==0){
               lastIndex=lastIndex-2;
               if (lastIndex==-1){
                   return 0;
               }
            }else {
                stones[--lastIndex]=left;
                (stones);
            }
        }
        return stones[lastIndex];
    }   
}

refer to

Non-sorting method - weight of the last stone - LeetCode

The above is the detailed content of the weight of the last stone of the Go language LeetCode problem solution 1046. For more information about the weight of the last stone of the Go problem solution, please pay attention to my other related articles!