题目描述
题目来源于leetcode
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
示例:
输入:s = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
简要分析
暴力求解。
从数组的每个索引开始,找到从当前索引 i 开始之后到索引 j 的值得和>=s,比较每个j-i+1的值,取最小。
代码
class Solution {
public int minSubArrayLen(int s, int[] nums) {
if(nums.length==0 || nums==null) {
return 0;
}
int result=Integer.MAX_VALUE;
for(int i=0;i<nums.length;i++) {
int b=0;
for(int j=i;j<nums.length;j++) {
b=b+nums[j];
if(b>=s) {
result = result<(j-i+1)?result:(j-i+1);
break;
}
}
}
if(result == Integer.MAX_VALUE){
return 0;
}else
return result;
}
}
优化
用双指针来解决此题
定义start、end两个指针,均初始化为0;
不断移动end,比较start~end下的值之和sum与s的大小
当sum>=s,取得end-start+1并更新为最小值,此时令sum=sum-nums[start],并移动start,回到第二步,继续判断sum与s的大小。
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int ans = Integer.MAX_VALUE;
int start = 0, end = 0;
int sum = 0;
while (end < n) {
sum += nums[end];
while (sum >= s) {
ans = Math.min(ans, end - start + 1);
sum -= nums[start];
start++;
}
end++;
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}
573

被折叠的 条评论
为什么被折叠?



