Monday, November 23, 2015

[leetcode]Minimum Size Subarray Sum

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int curSum = 0;
        int length = Integer.MAX_VALUE;
        int start = 0;
        boolean hasResult = false;
        for (int i = 0; i < nums.length; i++){
            if (nums[i] >= s) return 1;
            curSum += nums[i];
            while (curSum >= s){
                hasResult = true;
                length = Math.min(length, i-start+1);
                curSum -= nums[start++];
            }
        }
        
        return hasResult?length:0;
    }
}

No comments:

Post a Comment