leetcode@ [209]Minimum Size Subarray Sum

https://leetcode.com/problems/minimum-size-subarray-sum/

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        vector<int> vec = nums;
        
        for(int i=1;i<nums.size();++i){
            nums[i]+=nums[i-1];
        }
        
        int minLen = numeric_limits<int>::max();
        for(int i=0;i<nums.size();++i){
            int low = i, high = nums.size()-1, mid;
            while(low < high){
                mid = (low+high)/2;
                if(nums[mid]-nums[i]+vec[i] < s)  low = mid+1;
                else high = mid;
            }
            if(nums[low]-nums[i]+vec[i]>=s && low-i+1<minLen) minLen = low-i+1;
        }
        
        if(minLen == numeric_limits<int>::max()) return 0;
        else return minLen;
    }
};
原文地址:https://www.cnblogs.com/fu11211129/p/4927820.html