力扣 209题
给定一个含有 n 个正整数的数组和一个正整数 target 。找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0。
下面的代码是我自己想的一种方法,但是有问题:写出来只是用来扩展思路。
我的想法是,既然找最短的子数组其中元素之和,大于等于某个目标值,那我可以先给原数组排序,然后从最后一个元素开始遍历累加,当累加的和大于等于目标值,进行输出。但是其实这样得出的结果是---找到了最少的元素累加和,而不是原数组中的最短子数组。所以在力扣上跑的时候没有全部算例都通过。
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
sort(nums.begin(),nums.end());
int k = nums.size();
int sum = 0;
int count = 0;
int i = nums.size()-1;
while(sum < target)
{
sum += nums[i];
i--;
count++;
if(sum >= target)
{
return count;
break;
}
else if(count >