【LeetCode】1046. Last Stone Weight 最后一块石头的重量(Easy)(JAVA)每日一题

【LeetCode】1046. Last Stone Weight 最后一块石头的重量(Easy)(JAVA)

题目地址: https://leetcode.com/problems/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 <= stones.length <= 30
  • 1 <= stones[i] <= 1000

题目大意

有一堆石头,每块石头的重量都是正整数。

每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

  • 如果 x == y,那么两块石头都会被完全粉碎;
  • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
    最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。

解题方法

  1. 首先对整个数组进行排序
  2. 然后取出最大的两个数组,如果相等直接丢弃,不然把两者的差值插入排序好的数组,组成一个新的升序数组
  3. 这里用了最大堆,每次最大的值都在堆顶,取出两个最大的值,再把差值重新放入,时间复杂度: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();
    }
}

执行耗时:2 ms,击败了41.83% 的Java用户
内存消耗:35.7 MB,击败了85.05% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/111942674