给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 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
思路就是从数组第一位开始判断是否大于target,不大于就与后一位相加,一直加到大于target,记录加了几位,依次循环,第一次从第一位开始往后加,第二次从第二位开始往后加,找到加的次数最少的返回。
public int MinSubArrayLen(int target, int[] nums) {
int a = 0;
int res = 0;
int s = 0;
int sum = 0;
int x = 0;
List<int> lis = new List<int>();
if (nums.Max() >= target) return 1;
for (int i = 0; i < nums.Length; i++)
{
sum += nums[i];
}
if (sum < target) return 0;
if (sum == target) return nums.Length;
for (int j = 0; j < nums.Length; j++)
{
for (int i = s; i < nums.Length; i++)
{
x = x+1;
if (a < target)
{
a += nums[i];
if (a >= target)
{
res = x;
}
else
{
res = nums.Length;
}
}
else
{
if (a >= target)
{
break;
}
else
{
res = nums.Length;
}
}
}
lis.Add(res);
s++;
a = 0;
res = 0;
x = 0;
}
return lis.Min();
}