[leetcode] 330. Patching Array 解题报告

题目链接: https://leetcode.com/problems/patching-array/

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.


思路: 一个贪心的算法, 因为数组是排好序的, 因此我们从左到右遍历数组, 并且维护一个到当前为止最大可以到达的值, 如果当前数组的值比这个最大值大的话说明我们无法合成这个值, 需要补贴一个数, 然后加上补贴的这个数更新为新的最大可到达的值.举个栗子: nums = [1, 5, 10]n = 20

最初始状态, 我们能够cover的是小于1的数, 因此第一个遇到1正好可以cover下一个数, 因此不需要补贴, 这样我们可以更新最大可以cover的值为1*2 = 2以内的数.

第二个数组值为5, 而现在我们只能cover 2以内的数, 因此需要补贴一个2, 最大值变成了2*2 = 4. 也就是下次我们可以合成4以内的数.

然后仍然看数组的值5, 添加了2以后依然无法到达5, 因此我们需要再补贴一个值4, 之后我们最大可以到达的数变成了8以内的数.

在一次看数组值5, 这个5在可以cover的数范围内了, 因此可以遍历数组的下一个值了.而多了一个5之后我们可以到达的最大值变成了8+5 =13以内的值了 

下一个数组值为10, 依然在我们能够cover的值之内, 因此不需要补贴, 然后有了10之后能够cover的值的范围变成了13+10 =23 > 20, 因此我们只要补贴两个值即可.

代码如下:

class Solution {
public:
    int minPatches(vector<int>& nums, int n) {
        long cover = 1;
        int result = 0, i = 0;
        while(cover <= n)
        {
            if(i >= nums.size() || nums[i] > cover)
            {
                result++;
                cover = cover*2;
            }
            else if(i < nums.size())
            {
                cover += nums[i];
                i++;
            }
        }
        return result;
    }
};
参考: https://leetcode.com/discuss/83272/share-my-thinking-process















你可能感兴趣的:(LeetCode,greedy)