330. Patching Array
2016-05-20 09:47
309 查看
iven a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
Example 1:
nums = [1, 3], n = 6
Return 1.
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.
Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].
Example 3:
nums = [1, 2, 2], n = 5
Return 0.
这个应该是贪心的思想,假设[1,n)已经满足,那么接下来需要添加的数字就是n。
然后搜索一遍数组,如果数组num[i]的大小是在[1,n)范围内,那么就可以把这个数组加进去,
这个时候[1,n+num[i])的数字都是可以覆盖的;如果num[i]大于n,那么说明至少n
是无法被覆盖的,这个时候就需要把n加进去。
Example 1:
nums = [1, 3], n = 6
Return 1.
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.
Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].
Example 3:
nums = [1, 2, 2], n = 5
Return 0.
这个应该是贪心的思想,假设[1,n)已经满足,那么接下来需要添加的数字就是n。
然后搜索一遍数组,如果数组num[i]的大小是在[1,n)范围内,那么就可以把这个数组加进去,
这个时候[1,n+num[i])的数字都是可以覆盖的;如果num[i]大于n,那么说明至少n
是无法被覆盖的,这个时候就需要把n加进去。
class Solution { public: int minPatches(vector<int>& nums, int n) { int ans=0,i=0; long sum=0,tmp=1;//题目的数据比较大,会超过int类型的范围,必须用long while(tmp<=n){ if(i<nums.size()&&nums[i]<=tmp){ sum+=nums[i++]; tmp=sum+1; }else{ sum+=tmp; ans++; tmp=sum+1; } } return ans; } };
相关文章推荐
- django 中imagefield和filepathfiled的用法
- shell字符串的截取
- IOS-TableViewCell滑动删除
- 最全面的java多线程用法解析
- vickate_iOS_UITextField 的占位符自定义设置
- CodeForces-672C-Recycling Bottles
- z-stack/cc2530协议栈如何修改LED的设置及HalLedBlink的使用
- Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never diffe
- Box2D C++ 教程-力和冲量
- 使用百度地图API在页面添加百度地图应用
- Box2D C++ 教程-设置世界
- C/C++中extern关键字详解
- Binary Tree Postorder Traversal
- ScrollView嵌套ListView解决方案
- ASP.NET控件之CompareValidator控件
- FILEUTILS 介绍(Strtus 文件操作)
- netstat 命令state值
- 在Linux下安装Django
- Box2D C++ 教程-定制器
- 我是被你囚禁的鸟