• 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
    
    
    
     
  • 相关阅读:
    stm32 IO模式
    stm32的ADC
    bsp
    stm32的硬件调试设置
    RTC实时时钟
    快手2019笔试题 “回文子串" 解题思路
    C++内存修改器开源代码
    FC游戏修改教程(hack)小白文。
    GLFW+GLEW搭建opengl环境(备忘)
    8086 IO读写操作
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13418149.html
Copyright © 2020-2023  润新知