[LeetCode] 1046. Last Stone Weight (Easy) (JAVA) One question per day

[LeetCode] 1046. Last Stone Weight (Easy) (JAVA)

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

Title description:

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 <= stones.length <= 30
  • 1 <= stones[i] <= 1000

General idea

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. 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.

Problem-solving method

  1. Sort the entire array first
  2. Then take out the two largest arrays and discard them if they are equal, otherwise insert the difference between the two into the sorted array to form a new ascending array
  3. The largest heap is used here, each time the largest value is on the top of the heap, take out the two largest values, and then put the difference back in, time complexity: O(nlogn)
class Solution {
    public int lastStoneWeight(int[] stones) {
        PriorityQueue<Integer> queue = new PriorityQueue<>(stones.length, (a, b) -> (b - a));
        for (int i = 0; i < stones.length; i++) {
            queue.offer(stones[i]);
        }
        while (queue.size() > 1) {
            Integer large = queue.poll();
            Integer small = queue.poll();
            if (large == small) continue;
            queue.offer(large - small);
        }
        return queue.size() == 0 ? 0 : queue.poll();
    }
}

Execution time: 2 ms, beating 41.83% of Java users
Memory consumption: 35.7 MB, beating 85.05% of Java users

Welcome to pay attention to my official account, LeetCode updates one question every day

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/111942674