ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode 1046 最后一块石头的重量

2020-12-30 10:03:25  阅读:166  来源: 互联网

标签:stones 1046 integerPriorityQueue int 重量 石头 stoneStr new leetcode


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);
}

标签:stones,1046,integerPriorityQueue,int,重量,石头,stoneStr,new,leetcode
来源: https://www.cnblogs.com/fyusac/p/14209948.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有