您的位置:首页 > 职场人生

leetcoede之Patching Array

2016-03-04 13:09 302 查看
题目:

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
.

解答:

解法很巧妙,首先要知道一个定理就是1,2,4,8这样的2的幂的组合的和可以表示小于2^(n + 1) - 1的所有数

比如1,2,4三个数的和可以表示小于8的所有的数字

接下来用一个变量x表示最小的不能表示的数字,初始化为1(因为题目中要求表示的是[1,n]

接下来如果这个变量大于等于num,此时可以把该变量扩大为x + num(仔细想一下就知道,还没用已经可以表示到x - 1,用了num以后最大可以表示到x - 1 + num)

如果x小于num,就说明必须要插入x了,此时的最小的不能表示的变量就变成了x + x
Attention:由于x一直表示的都是目前不能表示的最小的数字,所以当n是INT_MAX的时候,会出现x溢出才能结束循环
所以X必须是long long型才可以,同时这种解法的前提是元数组已经是有序的了,注意leetcode上的很多题目都是必须要考虑边界问题的
class Solution {
public:
int minPatches(vector<int>& nums, int n) {

954e
long long int minRightBorder = 1;
int i = 0;
int res = 0;
while(minRightBorder <= n)
{
if(i < nums.size() && minRightBorder >= nums[i])
minRightBorder += nums[i++];
else
{
minRightBorder += minRightBorder;
res++;
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试