LeetCode Minimum Size Subarray Sum, leetcodesubarray

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.