C++, 6ms, easy to understand


  • 0
    S
    class Solution {
    public:
        int minSubArrayLen(int s, vector<int>& nums) {
            if(nums.empty()) return 0;
            int start = -1, sum = nums[0], minLen = INT_MAX;
            bool flag = false;
            if(sum >= s){
                start = 0;
                flag = true;
                minLen = 1;
            }
            for(int i = 1; i < nums.size(); i++){
                sum += nums[i];
                if(sum >= s){
                    if(flag == false){
                        start = 0;
                        flag = true;
                    }
                    while(sum-nums[start] >= s) sum -= nums[start++];
                    minLen = min(i-start+1, minLen);                
                }
            }
            if(start == -1) return 0;
            else return minLen;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.