描述:
给出n
个数,现在要将这n
个数合并成一个数,每次只能选择两个数a,b合并,每次合并需要消耗a+b
的能量,输出将这n
个数合并成一个数后消耗的最小能量。
算法:
贪心算法:显然每次选择当前的最小的两个数进行合并的答案是最优的,故用一个优先队列,大根堆,每次选堆顶的两个元素进行合并,然后再扔进堆里即可,时间复杂度O(nlogn)O(nlogn)。
代码实现(JAVA):
public int mergeNumber(int[] numbers) {
// Write your code here
// 1.将数组的数值添加进队列中
Queue<Integer> queue = new PriorityQueue<>();
for (int i = 0; i < numbers.length; i++) {
queue.add(numbers[i]);
}
int result = 0;
while (queue.size() > 1) {
int a = queue.poll();
int b = queue.poll();
result += (a + b);
queue.add(a + b);
}
return result;
}