Lintcode 791. Merge Number

给出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;
}

要想获取最小的消耗能量,采取的贪心策略当然是从小数开始合并,但同时要保证合并后要重新添加到数组中并保持顺序,因此优先队列是比较好的选择

猜你喜欢

转载自blog.csdn.net/qq_38702697/article/details/82956933