330. Patching Array【M】【84】【leetcode】
2016-03-18 12:22
447 查看
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range
Example 1:
nums =
Return
Combinations of nums are
Now if we add/patch
Possible sums are
So we only need
Example 2:
nums =
Return
The two patches can be
Example 3:
nums =
Return
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
[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
2to 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
1patch.
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution(object): def minPatches(self, nums, n): res = 0 cur = 1 total = 1 i = 0 while total <= n: if i < len(nums) and nums[i] <= total : #cur not in nums: #res += 1 total += nums[i] i += 1 else: res += 1 total += total #print nums,total return res
相关文章推荐
- C#中timer类
- SICP笔记(3)
- ViBe目标检测算法
- 【追求进步】矩形覆盖
- 将后台Activity移动到前台
- “霸王”条款:微信不绑卡就冻结账户
- 白手起家创业几年后年收入百万的故事
- [转]Struts2理解--动态方法和method属性及通配符_默认Action
- 分享一下我的jekyll主题
- 十字链表的建立
- Js操作cookie
- list分页
- 几组价量背离的图片,供学习分析
- 人生
- Lock & Condition
- Android 实现上下滚动TextSwitcher
- PHP 数据表结构的显示
- 【C/C++】C语言union(联合体 共用体)
- JavaScript数组length的方便与痛
- 慢启动快速恢复