2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_209.java 1.09 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2021-01-22 15:39 .
package com.hit.basmath.learn.array_and_string;
/**
* 209. 长度最小的子数组
* <p>
* 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
* <p>
* 示例:
* <p>
* 输入:s = 7, nums = [2,3,1,2,4,3]
* 输出:2
* 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
* <p>
* 进阶:
* <p>
* 如果你已经完成了 O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
*/
public class _209 {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0) return 0;
int headIndex = 0, tempIndex = 0, sum = 0, min = Integer.MAX_VALUE;
while (tempIndex < nums.length) {
sum += nums[tempIndex++];
while (sum >= s) {
min = Math.min(min, tempIndex - headIndex);
sum -= nums[headIndex++];
}
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助