LeetCode209 Minimum Size Subarray Sum

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). 

LINK:here

思路:

看到这种题首先想到的应该是滑动窗操作,我们使用两个指针记录窗口的左右边界,然后统计窗口中的值。使用滑动窗口最重要的一点是注意边界的更新条件。代码如下:

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int fast = 0, low = 0;  //用于存放滑动窗口的左右边界
        int minLen = INT_MAX;  //最小长度
        int sum = 0;  //存放窗口中元素的和
        while(fast < int(nums.size())){
            sum += nums[fast++];
            while(sum >= s){
                minLen = min(minLen, fast-low);
                if(minLen == 1) return 1;
                sum -= nums[low++];
            }
        }
        if(minLen == INT_MAX) return 0;
        else return minLen;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/89278139
今日推荐