Problem
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.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
</>复制代码
class Solution {
public int minSubArrayLen(int target, int[] nums) {
if (nums == null || nums.length == 0) return 0;
int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;
while (i <= j && j < nums.length) {
sum += nums[j];
while (sum >= target && i <= j) {
min = Math.min(min, j-i+1);
sum -= nums[i];
i++;
}
j++;
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72432.html
摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 公众号: 爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组...
摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 公众号: 爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组...
摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 算法是一个程序的灵魂 公众号:爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的...
摘要:如果不存在符合条件的连续子数组,返回。示例输入输出解释子数组是该条件下的长度最小的连续子数组。截取从索引到索引的数组,该数组之和若小于,则继续后移,直到大于等于。记录与差值返回的目标数。之后后移一位继续刷新新数组。 算法是一个程序的灵魂 公众号:爱写bug(ID:icodebugs)作者:爱写bug 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的...
摘要:双指针复杂度时间空间思路我们用两个指针维护一个窗口,保证这个窗口的内的和是小于目标数的。如果和仍小于目标数,则将窗口右边界右移。另外,如果左边界大于右边界时,说明最短子串的长度已经小于等于,我们就不用再查找了。 Minimum Size Subarray Sum Given an array of n positive integers and a positive integer ...
阅读 1521·2021-11-22 09:34
阅读 2688·2021-11-12 10:36
阅读 1201·2021-11-11 16:55
阅读 2407·2020-06-22 14:43
阅读 1535·2019-08-30 15:55
阅读 2052·2019-08-30 15:53
阅读 1837·2019-08-30 10:50
阅读 1293·2019-08-29 12:15