Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3]
has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
学习计算机网络的时候,get到了一种滑动窗口的思想,对于此类寻找连续字串的题目有很好的参考意义。首先从数组的最左边(最开始)一词累加,知道累加和大于等于输入值,然后从左边开始减少(考虑到数组是无序的),小于输入值则向右滑动。想了很久,才想到。。。
class Solution { public: int minSubArrayLen(int s, vector<int>&nums) { //滑动窗口的思想 int size = nums.size();//获取数组长度 int result=INT_MAX;//定义返回结果 int Sum = 0; //计算总和,用于比较 int begin = 0;//滑动窗口开始 for (int i = 0; i < size; i++) { Sum += nums[i]; //向数组右端开始累加 while (Sum >= s) {//满足要求时向右滑动,改变窗口开始begin的值 result = min(result, i - begin + 1); Sum -= nums[begin]; begin++; } } return result == INT_MAX ? 0 : result; } };