【LeetCode】Patching Array

来源:互联网 发布:笔记本强力卸载软件 编辑:程序博客网 时间:2024/04/28 22:53

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.
题目大意:
给定一个正整形递增数组num和正整数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;

class Solution {public:  int minPatches(vector<int>& nums, int n) {    long miss = 1;    int add = 0;    int i = 0;    while(miss<=n){      if(i<nums.size() && nums[i] <= miss){         miss += nums[i++];       }else {         miss += miss;         add++;         }     }        return add;    }};
0 0
原创粉丝点击