给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [nums l, nums l+1, …, nums r-1, nums r] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
提示:
1 <= target <= 10的9次方
1 <= nums.length <= 10的5次方
1 <= nums[i] <= 10的5次方
方法一:暴力方法一。提交会超时
//下面的代码思路上没有什么问题,但是提交的时候超时了。public int minSubArrayLen(int target, int[] nums) {//存放所有可能的结果ArrayList list = new ArrayList<>();for (int i = 0; i < nums.length; i++) {int size = 0;int temp = 0;for (int j = i; j < nums.length; j++) {temp += nums[j];size++;if (temp >= target) {list.add(size);//给所有大于等于target的数据都放到list中break;}}}if (list.size() == 0) {return 0;}int res = list.get(0);for (int i = 0; i < list.size(); i++) {res = res <= list.get(i) ? res : list.get(i);}return res;}
方法二:暴力方法二。和官方给出的题解的答案一样,仍然超时, 是因为答案中的输入案例有问题。
//超时。和官方给出的题解的答案一样,仍然超时, 是因为答案中的输入案例有问题。public int minSubArrayLen2(int target, int[] nums) {if (nums == null || nums.length == 0){return 0;}int res = Integer.MAX_VALUE;for (int i = 0; i < nums.length; i++) {int temp = 0;for (int j = i; j < nums.length; j++) {temp += nums[j];if (temp >= target) {res = Math.min(res, j - i + 1);break;}}}return res == Integer.MAX_VALUE ? 0 : res;}
方法三:滑动窗口。 这也是题目想让大家采用的方法
//滑动窗口。 这也是题目想让大家采用的方法//AC通过public int minSubArrayLen3(int target, int[] nums) {if (nums == null || nums.length == 0){return 0;}int res = Integer.MAX_VALUE;int start = 0;//窗口开始位置int end = 0;//窗口结束位置int sum = 0;//临时的求和结果,用来和target对比判断while (end < nums.length) {sum += nums[end];while (sum >= target) {res = res < end - start + 1 ? res : end - start + 1;sum -= nums[start];start++;}end++;}return res == Integer.MAX_VALUE ? 0 : res;}
LeetCode 200. 岛屿数量
LeetCode 201. 数字范围按位与
LeetCode 202. 快乐数
LeetCode 203. 移除链表元素
LeetCode 204. 计数质数
LeetCode 205. 同构字符串
LeetCode 206. 反转链表
LeetCode 207. 课程表
LeetCode 208. 实现 Trie (前缀树)
LeetCode 209. 长度最小的子数组
LeetCode 210. 课程表 II
声明:
题目版权为原作者所有。文章中代码及相关语句为自己根据相应理解编写,文章中出现的相关图片为自己实践中的截图和相关技术对应的图片,若有相关异议,请联系删除。感谢。转载请注明出处,感谢。
B站: https://space.bilibili.com/1523287361 点击打开链接
微博: http://weibo.com/luoyepiaoxue2014 点击打开链接
下一篇:OpenFeign问题汇总