leetcode-209 Minimum Size Subarray Sum

来源:互联网 发布:淘宝延迟收货是多久 编辑:程序博客网 时间:2024/05/21 12:35

采用类似滑动窗口的形式,.两个指针, start end, end向后走,直到 sum 大于 s. 然后start向后, 直到sum 小于s. 同时更新 min值.复杂度O(n)

O(n) time, O(1) space moving window method using a moving window [start,end] to calculate the sum, first move end forward to get a sub-array with sum>=s, then move start forward to make sum < s, then move end again,..., until end reach the end of array.

注意:nums和s都是正数

<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {public:    int minSubArrayLen(int s, vector<int>& nums) {        if(nums.size() == 0)  return 0;        int start = 0, end = 0, tmpsum = 0, len = nums.size(), res = len + 1;        while(end < len){            while(tmpsum < s && end < len) tmpsum += nums[end++];            while(tmpsum >= s) tmpsum -= nums[start++];            res = min(res,end - start + 1);        }        return res > len ? 0 : res;    }};</span>
还有种O(nlgn)的解法,可以参考:http://www.cnblogs.com/grandyang/p/4501934.html和https://leetcode.com/discuss/35289/moving-window-solution-space-another-binary-search-version

0 0
原创粉丝点击