题目地址:https://leetcode-cn.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. 1 <= sticks.length <= 10^4
  2. 1 <= sticks[i] <= 10^4

题目大意

为了装修新房,你需要加工一些长度为正整数的棒材 sticks。
如果要将长度分别为 X 和 Y 的两根棒材连接在一起,你需要支付 X + Y 的费用。 由于施工需要,你必须将所有棒材连接成一根。
返回你把所有棒材 sticks 连成一根所需要的最低费用。注意你可以任意选择棒材连接的顺序。

解题方法

小根堆

这个题是遇到过的微软面试题。

其实题目是让我们生成一个哈弗曼树,做法是使用小根堆,每次选用最小的两根棒材,拼接到一块,然后放入小根堆中。重复这个操作,直至小根堆中只有一个棒材为止。

C++代码如下:

class Solution {
public:
int connectSticks(vector<int>& sticks) {
priority_queue<int, vector<int>, greater<int>> que;
for (int stick : sticks) {
que.push(stick);
}
int res = 0;
while (!que.empty()) {
int first = que.top(); que.pop();
if (!que.empty()) {
int second = que.top(); que.pop();
int sum = first + second;
res += sum;
que.push(sum);
}
}
return res;
}
};

日期

2019 年 9 月 23 日 —— 昨夜睡的早,错过了北京的烟火

最新文章

  1. JavaScript 9种类型
  2. PhyLab2.0设计分析阶段任务大纲(α)
  3. Typecho中的gravatar头像无法加载
  4. sp_addlinkedserver 方法应用
  5. application/x-www-form-urlencoded
  6. NTT
  7. Spring Boot 环境变量读取 和 属性对象的绑定
  8. error_log() 范例
  9. Java Service Wrapper配置详解
  10. centos 软件安装 删除
  11. prototype对象的真正作用
  12. Hadoop1.2.1伪分布模式安装指南
  13. IIS缺少文件的解决方法
  14. KINGSO介绍
  15. asp.net 自定义的模板方法接口通用类型
  16. php的底层原理
  17. C# E店宝格格家接口对接
  18. Visual GC提示&quot;不受此JVM支持“解决方案(配置jstatd)
  19. Hibernate中的实体规则、对象状态和进阶-一级缓存
  20. docker1.13.1的安装与卸载及mysql5.5安装实例

热门文章

  1. spring通过注解注册bean的方式+spring生命周期
  2. Git常用操作(二)
  3. Boussinesq 近似及静压假定,内外模分离方法(附录A)
  4. Linux环境下R和R包安装及其管理
  5. 63. Binary Tree Level Order Traversal II
  6. Tikz绘制形似万花尺的图片
  7. 单元测试在Unity中的应用
  8. Spring整合Mybatis报 java.lang.ClassNotFoundException:org.springframework.core.metrics.ApplicationStartup,即:spring的版本过高,采用RELEASE稳定版
  9. A Child&#39;s History of England.33
  10. 安全相关,xss