接続スティックへの最小コスト

あなたはいくつか持っている  sticks 正の整数の長さを。

あなたは長さの任意の2本の棒接続できる  X と  Y のコストを支払うことにより、1本のスティックにします  X + Y残りの1本の棒があるまで、この操作を実行します。

与えられたすべての接続の最小コスト返し  sticks 、このように1本のスティックにします。

例1:

Input: sticks = [2,4,3]
Output: 14

例2:

Input: sticks = [1,8,3,5]
Output: 30

アイデア:PQ、加算の最小2つのうちの各ポールと;時間:O(nlogn)容量:O(N)

class Solution {
    public int connectSticks(int[] sticks) {
        if(sticks == null || sticks.length == 0) {
            return 0;
        }
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        for(int i = 0; i < sticks.length; i++) {
            pq.offer(sticks[i]);
        }
        int cost = 0;
        while(pq.size() >= 2) {
            int a = pq.poll();
            int b = pq.poll();
            pq.add(a + b);
            cost += (a + b);
        }
        return cost;
    }
}

 

公開された673元の記事 ウォン称賛13 ビュー180 000 +

おすすめ

転載: blog.csdn.net/u013325815/article/details/105176280