leetcode 1046 最后一块石头的重量

package com.example.lettcode.dailyexercises;

import java.util.PriorityQueue;
import java.util.Scanner;

/**
 * @Class LastStoneWeight
 * @Description 1046 最后一块石头的重量
 * 有一堆石头,每块石头的重量都是正整数。
 * 每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
 * 如果 x == y,那么两块石头都会被完全粉碎;
 * 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
 * 最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
 * <p>
 * 示例:
 * 输入:[2,7,4,1,8,1]
 * 输出:1
 * 解释:
 * 先选出 7 和 8,得到 1,所以数组转换为 [2,4,1,1,1],
 * 再选出 2 和 4,得到 2,所以数组转换为 [2,1,1,1],
 * 接着是 2 和 1,得到 1,所以数组转换为 [1,1,1],
 * 最后选出 1 和 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。
 * 提示:
 * 1 <= stones.length <= 30
 * 1 <= stones[i] <= 1000
 * @Author
 * @Date 2020/12/30
 **/
public class LastStoneWeight {
    /**
     * 利用堆排序
     *
     * @param stones
     * @return
     */
    public static int lastStoneWeight(int[] stones) {
        PriorityQueue<Integer> integerPriorityQueue = new PriorityQueue<>((o1, o2) -> o2.compareTo(o1));
        for (int i = 0; i < stones.length; i++) {
            integerPriorityQueue.offer(stones[i]);
        }
        while (integerPriorityQueue.size() > 1) {
            int s1 = integerPriorityQueue.poll();
            int s2 = integerPriorityQueue.poll();
            if (s1 == s2) continue;
            int tmp = Math.abs(s1 - s2);
            integerPriorityQueue.offer(tmp);
        }
        return integerPriorityQueue.size() > 0 ? integerPriorityQueue.poll() : 0;
    }
}
// 测试用例
public static void main(String[] args) {
	Scanner scanner = new Scanner(System.in);
	String[] stoneStr = scanner.nextLine().split(",");
	int[] stones = new int[stoneStr.length];
	for (int i = 0; i < stoneStr.length; i++) {
		stones[i] = Integer.parseInt(stoneStr[i].trim());
	}
//        int[] stones = new int[]{2, 7, 4, 1, 8, 1};
	int ans = lastStoneWeight(stones);
	System.out.println("LastStoneWeight demo01 result : " + ans);
}
posted @ 2020-12-30 09:55  枫叶艾辰  阅读(72)  评论(0编辑  收藏  举报