Title description ( portal )
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.
Example:
输入:[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],这就是最后剩下那块石头的重量。
Problem solving ideas
Method 1: sort violence
Sort the stones array, then subtract the two largest ones, update the difference to the len-1 subscript, and update the other to 0. Sort the array. .
It keeps looping like this, after each sorting, it is guaranteed that the two maximum values are subtracted, and the loop ends, and the remaining maximum value is the weight of the last remaining stone.
public int lastStoneWeight(int[] stones) {
Arrays.sort(stones);
int len = stones.length;
while (len-- >=0) {
stones[stones.length-1] = stones[stones.length-1] - stones[stones.length - 2];
stones[stones.length-2] = 0;
Arrays.sort(stones);
}
return stones[stones.length - 1];
}
Method 2: Big top pile
In-depth analysis of PriorityQueue
Use PriorityQueue priority queue to achieve a large pile, related usage can be viewed API and source code.
Construction method:
interface method:
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>((a, b) -> b - a);
/**
* 重写compare方法。
* 在此体现了所谓的"自定义":即根据自己所写逻辑来决定实现最大/小堆
*/
// a-b 则是小根堆
for (int stone : stones
) {
priorityQueue.offer(stone);
}
while (priorityQueue.size() > 1) {
int a = priorityQueue.poll();
int b = priorityQueue.poll();
if (a - b > 0) {
priorityQueue.offer(a - b);
}
}
return priorityQueue.isEmpty()?0:priorityQueue.poll();
}