码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Mininum Size Subarray Sum"

时间:2015-05-13 16:06:43      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

O(n): Sliding window:

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums)
    {
        int len = nums.size();
        if (len == 0) return 0;

        int w = INT_MAX;

        int i = 0, j = 0;
        int sum = nums[0];
        while (i <= j && j < len)
        {
            if (sum >= s)
            {
                w = std::min(w, j - i + 1);
                sum -= nums[i++]; // shrink
            }
            else // sum < s
            {
                j++; // expand
                if (j < len)    sum += nums[j];
            }
        }

        return w == INT_MAX ? 0 : w;
    }
};

O(nlgn) - this is the punch line of this problem
https://leetcode.com/discuss/35335/o-nlgn-is-not-that-easy-here-is-my-java-code 

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums)
    {
        int len = nums.size();
        if (len == 0) return 0;

        //    sums[i] : number sum from 0...i
        vector<int> sums(len, 0);
        sums[0] = nums[0];
        for (int i = 1; i < len; i++)
            sums[i] = sums[i - 1] + nums[i];
        if (sums.back() < s) return 0;

        int w = INT_MAX;

        for (int i = 0; i < len; i++)
        {            
            //    for each sum[i], find which k that, sum[k] - sum[i] + nums[i] >= s
            //    that is, sum of num[i..k]
            int l = i;
            int r = len - 1;
            while (l <= r)
            {
                int mid = l + (r - l) / 2;
                if (sums[mid] - sums[i] + nums[i] == s)
                {
                    l = mid;
                    break;
                }
                else if (sums[mid] - sums[i] + nums[i] < s)
                {
                    l = mid + 1;
                }
                else
                {
                    r = mid - 1;
                }
            }
            if (l >= len) break;
            w = std::min(w, l - i + 1);
        }

        return w == INT_MAX ? 0 : w;
    }
};

LeetCode "Mininum Size Subarray Sum"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4500575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!