My C++ solution with two pointers (easy to understand)


  • 0
    C

    Here is my C++ solution with two pointers a,b which represent begin and end respectively.

    In each loop, check whether sum is bigger than target.

    If sum is bigger, then update the min_len and move begin pointer to right
    else move end pointer to right.

    Here is the code:

    int minSubArrayLen(int target, vector<int>& nums) {
            if(nums.empty()) return 0;
            int a = -1;//begin pointer,at the first, it should be -1
            int b = -1;//end pointer
            int len = INT_MAX;//store the min len of the subarray
            int sum = 0;//sum
            // go until b reach to the end of the array
            while(b < (int)nums.size()){ 
                //if sum is smaller, then move b to the right, adds nums[b] to get the new sum
                if(sum<target){
                    b++;
                    sum += nums[b];
                }
                //if sum is bigger, then move a to the right, minus nums[a] to get the new sum
                //at the same time, update the min_len
                else{
                    len = min(len,b-a+1);
                    sum -= nums[a];
                    a++;
                }
            }
            return len == INT_MAX? 0 : len;//if not found, change len from INT_MAX to 0;
        }

Log in to reply
 

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