[Leetcode] 209 Minimum Size Subarray Sum, leetcodesubarray

Source: Internet
Author: User

[Leetcode] 209 Minimum Size Subarray Sum, leetcodesubarray

(1) O (logN) Solution

First, process the original array into the form of the forward and, so as to ensure the order of the array (note that the first is 0, push itself in), and then traverse the array, find the smallest subscript smaller than or equal to sum [I] + s. If it cannot be found, the break ends. Otherwise, continue and take the minimum value.

class Solution {public:    int minSubArrayLen(int s, vector<int>& nums) {     vector<int> sum;     int ans=100000000,temp=0;     sum.push_back(0);     for(int i=0;i<nums.size();i++)     {         temp+=nums[i];         sum.push_back(temp);     }     for(int i=0;i<sum.size();i++)     {         int n=lower_bound(sum.begin(),sum.end(),s+sum[i])-sum.begin();         if(n==sum.size())             break;         ans=min(ans,n-i);     }     if(ans==100000000)         return 0;     else          return ans;    }};
(2) O (N) Solution

The two pointers start end and end go backward until sum is greater than s. Then start is backward until sum is less than s. The min value is updated at the same time. It is similar to a sliding window.

public class Solution {    //1,1,4    public int minSubArrayLen(int s, int[] nums) {        //init check        int start = 0;        int end = 0;                int sum = 0;        int min = Integer.MAX_VALUE;                while(start<nums.length && end<nums.length) {            while(sum<s && end<nums.length) {                sum += nums[end++];            }            while(sum>=s && start<=end) {                min = Math.min(min, end-start);                sum -= nums[start++];            }        }        return min==Integer.MAX_VALUE ? 0 : min;    }}


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.