zoukankan      html  css  js  c++  java
  • leetcode209:长度最小的子数组

    1.题目描述

    给定一个含有 n 个正整数的数组和一个正整数 target 。

    找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。

    力扣链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum

    2.解题思路

    a.暴力求解,在需要一个最大的数的时候可以使用最大整数Integer.MAX_VALUE,在寻找较小的数可以使用Math.min(minLength, j - i + 1)

    3.代码

    public static int minSubArrayLen(int target, int[] nums) {
            int numsLength = nums.length;
            if (numsLength == 1) {
                if (target == nums[0]) {
                    return 1;
                } else {
                    return 0;
                }
            }
            // 维护一个大数据,使用最大的整数
            int minLength = Integer.MAX_VALUE;
            for (int i = 0; i < numsLength; i++) {
                // 有一个数和目标数相同,直接返回1
                if (nums[i] >= target) {
                    return 1;
                } else {
                    int temValue = nums[i];
                    for (int j = i + 1; j < numsLength; j++) {
                        temValue = temValue + nums[j];
                        if (temValue >= target) {
                            //更新最小长度
                            minLength = Math.min(minLength, j - i + 1);
                            break;
                        }
                    }
                }
            }
            // 判断是否为最初始的值,如果是返回0,不是则返回对应的长度
            return minLength == Integer.MAX_VALUE ? 0 : minLength;
        }
    

      

  • 相关阅读:
    IE6不支持hover赋予css样式的解决方法 如div:hover li:hover支持
    导航条
    check的css样式
    css3网站
    时间轴滚动充盈
    html5网站
    图片查看插件
    响应式列表中控制图片高度一致js
    json数组按xxx属性值排序 升序
    H5响应式方案
  • 原文地址:https://www.cnblogs.com/neverland0718/p/14456275.html
Copyright © 2011-2022 走看看