I. Title Description
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such this any number in range [1, n]inclusive can 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 .
Two. Topic analysis
The main idea of the topic is that given an array nums and a number n , adding the fewest number allows [1, n] each number in the interval to be nums composed of elements in the array.
Since the array is already sorted, the basic idea is to define an shaping variable currSum , assuming that the array nums currently can be added to the range of numbers [1, currSum) , and if you add an element () to the array at this point, k k <= currSum You can expand the range of accumulated numbers to [1, currSum + k) , The topic requires nums the least number of elements to be added to the array, so the k = currSum range of the accumulated numbers can be capped when and only if [1, 2 * currSum) . numsThere are two things to do when iterating through an array:
- When there are elements less than or equal to Currsum in the array
nums[index] , the elements in the array are used, while currSum += nums[index] ;
- If not, add a new element currsum into the array, at which time the range is extended to the maximum, while the
currSum <<= 1 .
Three. Sample code
#include <iostream>#include <vector>using namespace STD;classSolution { Public:intMinpatches ( vector<int>& Nums,intN) {intresult =0, index =0;//Currsum marks the maximum range that the current array nums can accumulate [1, currsum) for(intCurrsum =1; Currsum <= N; ) {when the element in the array is less than currsum, the cumulative sum cap is increased to //Currsum + Nums[index], then array index value plus 1 if(Index < Nums.size () && Nums[index] <= currsum) currsum + = nums[index++];Else{Currsum <<=1;adds an additive sum range to double++result; } }returnResult }};
Four. Summary
This method is not easy to think immediately, for this type of problem, in particular, the need to cite more examples on paper, slowly find out the law.
Leetcode Notes: Patching Array