您的位置:首页 > 其它

leetcode-209 Minimum Size Subarray Sum

2015-05-16 15:24 357 查看
采用类似滑动窗口的形式,.两个指针, 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: