330. Patching Array
2016-04-30 00:11
281 查看
Given 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.
贪心算法,每次算出能到达的最大的值max,如果能到达比nums[i]小1的值,这就保证了1到nums[i]-1都能得到,故1到nums[i]+max都能取得,就能更新max值和使i+1.如果max比nums[i]-1小,说明还不能到达nums[j],则先加上比max大1的数(补上这个数),更新max.需要注意的是,如果i超过了nums数的个数,也是每次更新max使其加上比它大1的数.
代码:
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.
贪心算法,每次算出能到达的最大的值max,如果能到达比nums[i]小1的值,这就保证了1到nums[i]-1都能得到,故1到nums[i]+max都能取得,就能更新max值和使i+1.如果max比nums[i]-1小,说明还不能到达nums[j],则先加上比max大1的数(补上这个数),更新max.需要注意的是,如果i超过了nums数的个数,也是每次更新max使其加上比它大1的数.
代码:
class Solution { public: int minPatches(vector<int>& nums, int n) { long long max=0; int count=0,len=nums.size(); for(int i=0;max<n;) { if(i>=len||max<nums[i]-1) { max+=max+1; count++; } else { max+=nums[i++]; } } return count; } };
相关文章推荐
- LeetCode刷题笔记(贪心):jump-game-ii
- LeetCode刷题笔记(贪心):maximum-subarray
- LeetCode刷题笔记(贪心):jump-game
- LeetCode刷题笔记(贪心):maximal-rectangle
- LeetCode刷题笔记(贪心):gas-station
- ZOJ 3953 Intervals
- LeetCode week 5 : Assign Cookies
- javascript: 基于原型的面向对象编程
- spring 依赖注入DI-个人学习笔记
- datalab 数据表示实验
- Javascript中的自执行匿名函数
- CodeForces 567D One-Dimensional Battle Ships
- MAC下apache+php
- android源码解析(十七)-->Activity布局加载流程
- 求方程的近似解
- Android 单元测试--系列一
- 日志收集之kafka
- iOS开发 - CocoaPods安装和使用教程
- java利用递归解决八皇后问题
- 求方程的近似解,不用库函数求一个数的平方根