Java Solution using Sliding Window


  • 0
    A
    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            int result = Integer.MAX_VALUE;
            int sum = 0;
            int prev = 0;
            int curr = 0;
            boolean flag = false;
            while(curr < nums.length) {
                sum += nums[curr];
                if(sum >= s){
                    while(sum >= s){
                        flag = true;
                        result = Math.min(result, curr-prev+1);
                        sum -= nums[prev];
                        prev++;
                    }
                }
                curr++;
            }
            if(!flag){
                return 0;
            }
            return result;
        }
    }

  • 0
    G

    Thanks a lot. I gradually understand what is "slide window" algrithm :--)
    and here is my slidewindow code

    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.