Java AC solution using two pointers


  • 11
    J

    Using two pointers to solve this question

    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            if(nums.length == 0)return 0;       
            int first = 0;
            int second = 0;
            int min = nums.length+1;
            int sum = nums[0];
            while(first<nums.length && second<=first)
            {
                
                if(sum<s){
                    first++;
                    if(first<nums.length)
                    sum+= nums[first];
                }
                else {
                    min = Math.min(first-second+1, min);
                    sum-=nums[second];
                    second++;
                    
                }
            }
            
            if(min == nums.length+1)return 0;
            return min;
        }
    }

  • 2
    C

    Cool solution!

    I think in the initialization, min should be nums.length+1 instead of nums.length.

    And at last, instead of

    if(min == nums.length)return 0;
    

    it should be

    if(min == nums.length+1) return 0;

  • 0
    J

    Yes, you're right! Thank you so much.


Log in to reply
 

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