给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 >= target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。
如果不存在符合条件的子数组,返回 0 。
目前只能完善的写出暴力解法,其他解法还在探索中...
#include#include #include using namespace std; class Solution { public: int minSubArrayLen(int target, vector & nums) { // 暴力解法 空间复杂度为O(n^2) // 依次向后叠加比较值即可 int subLength = 0; //子数组长度 int result= INT32_MAX ; int sum = 0; for (int i = 0; i < nums.size(); i++) { sum = 0; for (int j = i; j < nums.size(); j++) { sum += nums[j]; if (sum >= target) { // 当子序列和大于等于目标值,就更新result subLength = j - i + 1; // 当前子序列长度 result = result < subLength ? result : subLength; break; // 找到符合的子序列即可跳出内层循环 } } } // 如果result没有被修改就返回0; return result == INT32_MAX ? 0 : result; } };



