Leetcode Note: Patching Array
I. Description
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]Specified sive 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
Return1.
Ii. Question Analysis
Given an arraynumsAnd numbernTo add the minimum number to make the interval[1, n]Each number in can be composed of an arraynumsElement accumulation.
Since the array has been sorted, the basic idea is to define an integer variable.currSumSuppose the range of the number that can be accumulated by the array nums is[1, currSum)If you add an element to the arrayk(k <= currSum) You can expand the range of accumulated numbers[1, currSum + k)And the question must be directed to the arraynumsThe number of elements added is the least, so if and onlyk = currSumYou can obtain the upper limit of the cumulative number range.[1, 2 * currSum). In the traversal ArraynumsYou can perform the following two operations:
When the array contains elements less than or equal to currSum
nums[index]Use the elements in the array
currSum += nums[index]; If no, add the new element currSum into the array. The range is extended to the maximum.
currSum <<= 1.
Iii. Sample Code
# Include
# Include
Using namespace std; class Solution {public: int minPatches (vector
& Nums, int n) {int result = 0, index = 0; // currSum indicates the maximum value range that nums can be added to the current array [1, currSum) for (int currSum = 1; currSum <= n;) {// when the number of elements in the array is smaller than currSum, the maximum value of sum that can be accumulated is // currSum + nums [index]. then the array index value is added with 1 if (index <nums. size () & nums [index] <= currSum) currSum + = nums [index ++]; else {currSum <= 1; // after adding an element, the sum range that can be accumulated is doubled + + result;} return result ;}};
Iv. Summary
This method is not easy to think of immediately. For this type of problem, we need to list more examples on paper to find out the rules.