通过万岁!!!
java代码——超时
class Solution {
public int minStoneSum(int[] piles, int k) {
int sum = Arrays.stream(piles).sum();
if (k == 0) {
return sum;
}
Arrays.sort(piles);
int lastIdx = piles.length - 1;
int currIdx;
for (int i = 0; i < k; i++) {
int divRes = piles[lastIdx] / 2;
piles[lastIdx] -= divRes;
sum -= divRes;
// 自己进行冒泡
currIdx = lastIdx;
while (currIdx - 1 >= 0 && piles[currIdx] < piles[currIdx - 1]) {
// 交换currIdx和currIdx-1
piles[currIdx] = piles[currIdx] + piles[currIdx - 1];
piles[currIdx - 1] = piles[currIdx] - piles[currIdx - 1];
piles[currIdx] = piles[currIdx] - piles[currIdx - 1];
currIdx--;
}
}
return sum;
}
}
java代码——不超时
class Solution {
public int minStoneSum(int[] piles, int k) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((a, b) -> b - a);
int sum = 0;
for (int i = 0; i < piles.length; i++) {
priorityQueue.offer(piles[i]);
sum += piles[i];
}
for (int i = 0; i < k; i++) {
Integer max = priorityQueue.poll();
priorityQueue.offer(max - max / 2);
sum -= max / 2;
}
return sum;
}
}