Share my 7ms solution with c++


  • 0
    J

    using two pointers

    class Solution {
    public:
    	int minSubArrayLen(int s, vector<int>& nums) {
    		int len = nums.size();
    		if (len <= 0) return 0;
    		int minLen = len + 1;
    		int i = 0, j = 0, sum = 0;
    		while (j <= len)
    		{
    			if (sum >= s)
    			{
    				minLen = j - i < minLen ? j - i : minLen;
    				sum -= nums[i++];
    			}else
    				sum += nums[j++];
    		}
    		if (minLen == len + 1)      // no solution 
    			return 0;
    		else                      
    			return minLen;
    	}
    };

  • 0
    L

    When j == len && sum < s, you try to access nums[len].


  • 0
    J

    yeah, big bug, i can add one element into vector nums to avoid the access.


Log in to reply
 

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