给出n
个数,现在要将这n
个数合并成一个数,每次只能选择两个数a,b合并,每次合并需要消耗a+b
的能量,输出将这n
个数合并成一个数后消耗的最小能量。
public int mergeNumber(int[] numbers) {
// Write your code here
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
for (int i: numbers) {
priorityQueue.add(i);
}
int sum = 0;
while (priorityQueue.size() > 1){
int first = priorityQueue.poll();
int second = priorityQueue.poll();
sum += first + second;
priorityQueue.add(first + second);
}
return sum;
}
要想获取最小的消耗能量,采取的贪心策略当然是从小数开始合并,但同时要保证合并后要重新添加到数组中并保持顺序,因此优先队列是比较好的选择