Java, Solved By Slide Window Algrithm :--)


  • 0
    G
    public static int minSubArrayLen(int s, int []nums){
    		int i=0,j=0;//2 pointers
                    //initialize the min:record the min subarray length
    		int min=Integer.MAX_VALUE;
    		int total=0;//record the sum
    		while(j<nums.length){
    			if(total<s){//continue sum until total>=s
    				total+=nums[j];
    				j++;
    			}
    			while(total>=s){//narrow the length
                                    //reset min if the length narrowed
    				min=(j-i)<min?(j-i):min;
    				total-=nums[i];
    				i++;
    			}
    		}
                    //if min's value not changed, then all sum is smaller than s
    		return min==Integer.MAX_VALUE?0:min;
    	}

Log in to reply
 

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