、
法一:滑动窗口
//使用滑动窗口来解决问题
//滑动窗口的核心点有:
/*1.窗口内是什么?2.如何移动窗口的起始位置?3.如何移动窗口的结束位置?4.两个指针,怎么判断哪个指针是终止指针,哪个指针是起始指针5.判断条件的时候使用if还是while
*/
int minSubArrayLen(int target, int* nums, int numsSize) { int minLength = INT_MAX;int sum = 0;int i = 0; //定义起始指针int j = 0; //定义终止指针for(;j < numsSize; j++){ //注意这里的j取不取等号sum = sum + nums[j]; //滑动的这一组窗口while(sum >= target){ //这里要想清楚第5点int subLeng = j - i + 1;minLength = minLength < subLeng ? minLength : subLeng;sum = sum - nums[i]; //滑动之前要减去滑走的值i++; //开始滑动}}return minLength == INT_MAX ? 0 : minLength;
}
法二:暴力破解(两个for循环)
int minSubArrayLen(int target, int* nums, int numsSize){//初始化最小长度为INT_MAXint minLength = INT_MAX;int sum;int left, right;for(left = 0; left < numsSize; ++left) {//每次遍历都清零sum,计算当前位置后和>=target的子数组的长度sum = 0;//从left开始,sum中添加元素for(right = left; right < numsSize; ++right) {sum += nums[right];//若加入当前元素后,和大于target,则更新minLengthif(sum >= target) {int subLength = right - left + 1;minLength = minLength < subLength ? minLength : subLength;}}}//若minLength不为INT_MAX,则返回minLnegthreturn minLength == INT_MAX ? 0 : minLength;
}