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;    }};

0 0
原创粉丝点击