LeetCode Minimum Size Subarray Sum, leetcodesubarray
Question
Ideas
The O (n) method is simple. You can simply use two subscripts to scan them;
O (nLogn) is a little difficult. In my opinion, we should first get the Sum of Sum [I] (I + 1) numbers. Because the numbers are all positive numbers, we can use the Sum array for binary search. We can scan Sum and then find the position of the first Sum that meets the condition in the second part.
Code
O (n ):
int minSubArrayLen(int s, int * nums, int numsSize) { int sum = nums[0], head = 0, tail = 0, minL = numsSize + 1; while (tail < numsSize) { if (tail - head + 1 < minL && sum >= s) minL = tail - head + 1; if (sum >= s) sum -= nums[head++]; else sum += nums[++tail]; if (head > tail) tail = head; } return minL == numsSize + 1 ? 0 : minL;}
O (nLogn ):
// Search for the position of a number that is smaller than the target in the sequence that does not decrease, that is, the location where the last number is smaller than the target. // search a number that is exactly less than 'target ', which means the last number less than 'target' int binarySearchIncreaseLastSmaller (int l, int r, int target, int * nums) {if (l> = r) return-1; while (l <r-1) {int m = l + (r-l)> 1); if (nums [m] <target) l = m; else r = m-1;} if (nums [r] <target) return r; else if (nums [l] <targ Et) return l; else return-1;} int minSubArrayLen (int s, int * nums, int numsSize) {int * Sum = (int *) malloc (sizeof (int) * (numsSize + 1), minL = numsSize + 1; Sum [0] = 0; for (int I = 1; I <= numsSize; I ++) sum [I] = Sum [I-1] + nums [I-1]; for (int I = 1; I <= numsSize; I ++) {if (Sum [I]> = s) {int k = Sum [I]; int BeforePos = binarySearchIncreaseLastSmaller (0, I, Sum [I]-s + 1, sum); if (Bef OrePos! =-1 & I-BeforePos <minL) minL = I-BeforePos;} return minL = numsSize + 1? 0: minL ;}