209. Minimum Size Subarray Sum 结果大于等于目标的最小长度数组

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

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

思路:就是前向指针,双重for循环。难得独立完成了

注意每次i的循环结束后,需要重新设置sum = 0

注意下sum >= s,最后的结果d需要+1

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int sum = 0;
        int d = Integer.MAX_VALUE;
        
        //cc
        if (nums == null || nums.length == 0)
            return 0;

        for (int i = 0; i < nums.length; i++) {
            for (int j = i; j < nums.length; j++) {
                //从i加到j
                sum += nums[j];
                if (sum >= s) {
                    d = Math.min(j - i, d);
                    
                    System.out.println("sum = " + sum);
                    System.out.println("j = " + j);
                    System.out.println("i = " + i);
                    System.out.println("j - i = " + (j - i));
                    System.out.println(" ");
                    
                    continue;
                }    
            }
            sum = 0;
        }
        
        if (d == Integer.MAX_VALUE)
            return 0;
        else return d + 1;
    }
}
View Code

 

 
posted @ 2020-08-02 11:07  苗妙苗  阅读(145)  评论(0编辑  收藏  举报