leetcode_330 Patching Array
来源:互联网 发布:绘画理论书 知乎 编辑:程序博客网 时间:2024/06/14 07:11
题目分析:
给定一个递增的正整数数组nums和正整数n,利用该数组中的数相加,实现1到n之间的所有数,求至少需要在数组中添加几个数来实现这一要求。
解题思路:
对于数组中,几个整数相加所能表示的返回时[1,m),则加上一个正整数n(n < m),则加完后的数据范围为[1,m)+n=[1+n,m+n)=[1,m+n);
故初始设定范围为[0,1),即一个数都不能表示,依次遍历数组num,比较num数组的当前值和已知范围的右边界m,主要包括两种情况:
- 1)若num[i] <= m,则直接扩展右边界为m = m + num[i];
- 2)若num[i] > m,不能直接扩展,需要添加一个数m,并且扩展右边界m = m + m;
实现程序
C++版本
class Solution{ public: int minPatches(vector<int> &nums, int n) { // 统计需要添加的元素数目 int count = 0; int i = 0; // 遍历进行判断 for (long temp_sum = 1; temp_sum <= n; ) { // nums[i] <= temp_sum情况,不需添加 if (i < nums.size() && nums[i] <= temp_sum) { temp_sum += nums[i++]; } // nums[i] >= temp_sum情况,需要添加,次数最大和为2 * temp_sum else { temp_sum <<= 1; count++; } } // 返回最后需要添加的数目 return count; }};
Java版本
public int minPatches(int[] nums, int n){ // 用于统计需要添加元素的数目 int count = 0; int i = 0; for (long temp_sum = 1; temp_sum <= n; ){ if (i < nums.length && nums[i] <= temp_sum){ temp_sum += nums[i++]; } else { temp_sum <<= 1; count++; } } return count;}
参考文献
https://www.hrwhisper.me/leetcode-patching-array/
http://m.blog.csdn.net/article/details?id=51337598
0 0
- leetcode_330 Patching Array
- Patching Array
- Patching Array
- Patching Array
- Patching Array
- leetcode Patching Array
- [LeetCode] Patching Array
- 330. Patching Array
- LeetCode330. Patching Array【贪心】
- leetcode笔记:Patching Array
- Leetcode: Patching Array
- leetcode 330. Patching Array
- Leetcode Patching Array
- [leetcode]330. Patching Array
- leetcoede之Patching Array
- [LeetCode]330. Patching Array
- leetcode330:Patching Array(贪心)
- [LeetCode 330] Patching array
- 字符串处理编程题
- Android面试经典 Application的作用
- 通过声卡拷贝/传输文件的技术原理
- 安卓开发资料链接
- MySQL索引的创建原则
- leetcode_330 Patching Array
- openGL 中的glMatrixMode 以及对应参数的含义
- 游标的使用
- WebSocket入门教程(四)-- WebSocket实例:实时获取服务器内存使用情况(优化一)
- c++作业7
- 浅谈android中异步加载之"取消异步加载"二
- 将Ubuntu 14.06配置成Web服务器
- 数学建模__药品研发任务分配
- Spring之IOC