【LeetCode】1167. Minimum Cost to Connect Sticks 解题报告 (C++)
2024-09-01 19:27:25
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址: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 <= sticks.length <= 10^4
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 日 —— 昨夜睡的早,错过了北京的烟火
最新文章
- JavaScript 9种类型
- PhyLab2.0设计分析阶段任务大纲(α)
- Typecho中的gravatar头像无法加载
- sp_addlinkedserver 方法应用
- application/x-www-form-urlencoded
- NTT
- Spring Boot 环境变量读取 和 属性对象的绑定
- error_log() 范例
- Java Service Wrapper配置详解
- centos 软件安装 删除
- prototype对象的真正作用
- Hadoop1.2.1伪分布模式安装指南
- IIS缺少文件的解决方法
- KINGSO介绍
- asp.net 自定义的模板方法接口通用类型
- php的底层原理
- C# E店宝格格家接口对接
- Visual GC提示";不受此JVM支持“解决方案(配置jstatd)
- Hibernate中的实体规则、对象状态和进阶-一级缓存
- docker1.13.1的安装与卸载及mysql5.5安装实例
热门文章
- spring通过注解注册bean的方式+spring生命周期
- Git常用操作(二)
- Boussinesq 近似及静压假定,内外模分离方法(附录A)
- Linux环境下R和R包安装及其管理
- 63. Binary Tree Level Order Traversal II
- Tikz绘制形似万花尺的图片
- 单元测试在Unity中的应用
- Spring整合Mybatis报 java.lang.ClassNotFoundException:org.springframework.core.metrics.ApplicationStartup,即:spring的版本过高,采用RELEASE稳定版
- A Child&#39;s History of England.33
- 安全相关,xss