题目:
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

解答:
o(n)

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        //移动的窗口,求连续在一起最短的满足条件的subarray
        int sum = 0, count = Integer.MAX_VALUE;
        int i = 0, j = 0;
        
        while (j < nums.length) {
            sum += nums[j];
            j++;
            while (sum >= s) {
                count = Math.min(count, j - i);
                sum -= nums[i];
                i++;
            }
        }
        
        return count == Integer.MAX_VALUE ? 0 : count;
    }
}

guoluona
199 声望14 粉丝

引用和评论

0 条评论