Leetcode: Patching Array
来源:互联网 发布:java list转map 编辑:程序博客网 时间:2024/05/08 07:38
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
.
比较巧妙的想法:计算数组中的累加和sum,如果不能cover住数字i,则patch一个数(sum+1)。比如 [1, 5, 10],从左到右扫描,不能cover住2,加上数字2,这时累加和更新为3;再不能cover住4,加上数字4,累加和为7;遇到5,累加和为12,然后6, 7, 8, 9, 10都可以cover住。
实现起来不能从1到n遍历,会超时;用sum来比较。
class Solution {public: int minPatches(vector<int>& nums, int n) { int patchCount = 0; long long prevSum = 0; int idx = 0; while (prevSum < n) { if (idx < nums.size() && nums[idx] <= prevSum + 1) { prevSum += nums[idx++]; } else { ++patchCount; prevSum += prevSum + 1; } } return patchCount; }};
- leetcode Patching Array
- [LeetCode] Patching Array
- leetcode笔记:Patching Array
- Leetcode: Patching Array
- leetcode 330. Patching Array
- Leetcode Patching Array
- [leetcode]330. Patching Array
- [LeetCode]330. Patching Array
- [LeetCode 330] Patching array
- 【LeetCode-330】Patching Array
- LeetCode Patching Array
- LeetCode Patching Array
- LeetCode *** 330. Patching Array
- 【LeetCode】Patching Array
- leetcode Patching Array
- 【LeetCode】330. Patching Array
- 【Leetcode】Patching Array
- LeetCode 330. Patching Array
- YTU 2642: 填空题:类模板---求数组的最大值
- STL之string
- ipvs负载均衡(三)ipvs三种工作方式
- Linux下的Nginx安装
- YTU 2677: 韩信点兵
- Leetcode: Patching Array
- YTU 2690: 用双重循环实现小九九
- 1.以普通表格型单表为模板定制模块:短信分类维护
- eclipse配置安卓环境(mac系统)
- 程序只运行一个实例,并激活已运行的程序
- YTU 2697: 血型统计
- BZOJ 1648 USACO 2006 Dec Cow Picnic 奶牛野餐 搜索
- POJ 3233 矩阵的幂(求和)
- YTU 2500: 二元表达式计算