/*有一堆石头,每块石头的重量都是正整数。 每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下: 如果 x == y,那么两块石头都会被完全粉碎; 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。 最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。 示例: 输入:[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],这就是最后剩下那块石头的重量。*/ import java.util.Scanner; import java.util.Arrays; public class LeetCode1046 { //直接给数组赋值 /*public static void main(String[] args) { int[] List1 = new int[]{2, 7, 4, 1, 8, 1}; System.out.println(Arrays.toString(List1)); Solution number = new Solution(); number.lastStoneWeight(List1); }*/ //键盘输入数字,转换成数组 public static void main(String[] args) { System.out.println("请输入几个数字并用逗号隔开:"); Scanner sc = new Scanner(System.in); String str = sc.next(); String[] arr = str.split(","); int[] number = new int[arr.length]; for (int i = 0; i < number.length; i++) { number[i] = Integer.parseInt(arr[i]); } //调用Array类中的toString方法(返回包含数组元素的字符串,写在括号内,元素用逗号隔开) //System.out.print(Arrays.toString(number)); Solution n1 = new Solution(); //定义一个整数变量用来接收返回结果 int result = n1.lastStoneWeight(number); System.out.println("最后一块石头的重量:" + result); //System.out.println(n1.lastStoneWeight(number)); } } class Solution { public int lastStoneWeight(int[] stones) { if (stones.length == 1) { return stones[0]; } int stoneCount = stones.length; int lastOne = stones.length - 1; int lastTwo = lastOne - 1; Arrays.sort(stones); while (stoneCount > 1) { if (stones[lastOne] == stones[lastTwo]) { stones[lastOne] = 0; stones[lastTwo] = 0; stoneCount -= 2; } else { stones[lastOne] = stones[lastOne] - stones[lastTwo]; stones[lastTwo] = 0; stoneCount -= 1; } Arrays.sort(stones); } if (stoneCount == 0) { return stones[0]; } else { //System.out.println("最后一块石头的重量:" + stones[lastOne]); return stones[lastOne]; } } }
Java学习笔记之 最后一块石头的重量
这篇博客通过一个Java程序解决了LeetCode上的1046题,即给定一组正整数石头,每回合选取两块最重的石头进行粉碎,根据规则更新石头的重量,直至只剩一块或没有石头。博主通过示例详细解释了算法思路,最终返回最后一块石头的重量。
摘要由CSDN通过智能技术生成