LC.P2208[将数组和减半的最少操作次数]

方法一:贪心+优先队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int halveArray(int[] nums) {
int ans = 0;
PriorityQueue<Double> q = new PriorityQueue<>((a, b) -> b.compareTo(a));
double sum = 0, newSum = 0;
for (int num : nums) {
q.offer((double) num);
sum += num;
}
while (newSum < sum / 2) {
double x = q.poll();
newSum += x / 2;
q.offer(x / 2);
++ans;
}
return ans;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$