首页 > 其他 > 详细

LeetCode 1167. Minimum Cost to Connect Sticks

时间:2020-01-10 09:37:57      阅读:80      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/minimum-cost-to-connect-sticks/

题目:

You have some sticks with positive integer lengths.

You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y.  You perform this action until there is one stick remaining.

Return the minimum cost of connecting all the given sticks into one stick in this way.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= sticks.length <= 10^4
  • 1 <= sticks[i] <= 10^4

题解:

Find the routine that add the two smallest first, then largest repeated the least times.

Use min heap to get two 2 smallest values, merge them and add merged back to min heap unitl there is only one stick in min heap.

Time Complexity: O(nlogn). n = sticks.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int connectSticks(int[] sticks) {
 3         if(sticks == null || sticks.length < 2){
 4             return 0;
 5         }
 6         
 7         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
 8         for(int num : sticks){
 9             minHeap.add(num);
10         }
11         
12         int res = 0;
13         while(minHeap.size() > 1){
14             int merge = minHeap.poll() + minHeap.poll();
15             res += merge;
16             minHeap.add(merge);
17         }
18         
19         return res;
20     }
21 }

 

LeetCode 1167. Minimum Cost to Connect Sticks

原文:https://www.cnblogs.com/Dylan-Java-NYC/p/12174241.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!