Skip to content

Commit a4722fe

Browse files
committed
2208. 将数组和减半的最少操作次数
1 parent be516aa commit a4722fe

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.gatsby;
2+
3+
import java.util.Comparator;
4+
import java.util.PriorityQueue;
5+
6+
/**
7+
* @ClassName: _2208MinimumOperationsToHalveArraySum
8+
* @Description: leetcode 2208 将数组和减半的最少操作次数
9+
* @author: Gatsby
10+
* @date: 2022/7/19 13:17
11+
*/
12+
13+
public class _2208MinimumOperationsToHalveArraySum {
14+
public int halveArray(int[] nums) {
15+
long sum = 0;
16+
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
17+
@Override
18+
public int compare(Integer o1, Integer o2) {
19+
return o2-o1;
20+
}
21+
});
22+
for (int num : nums) {
23+
priorityQueue.add(num);
24+
sum += num;
25+
}
26+
double half = (double) sum / 2;
27+
double currentSum = sum;
28+
int count = 0;
29+
System.out.println(sum);
30+
while (half < currentSum) {
31+
int max = priorityQueue.poll();
32+
max /= 2;
33+
currentSum -= max;
34+
priorityQueue.add(max);
35+
count++;
36+
System.out.println(currentSum);
37+
}
38+
return count;
39+
}
40+
}
41+
42+

0 commit comments

Comments
 (0)