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

leetcode@ [209]Minimum Size Subarray Sum

时间:2015-11-01 16:32:57      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/minimum-size-subarray-sum/

 

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn‘t one, return 0 instead.

 

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        vector<int> vec = nums;
        
        for(int i=1;i<nums.size();++i){
            nums[i]+=nums[i-1];
        }
        
        int minLen = numeric_limits<int>::max();
        for(int i=0;i<nums.size();++i){
            int low = i, high = nums.size()-1, mid;
            while(low < high){
                mid = (low+high)/2;
                if(nums[mid]-nums[i]+vec[i] < s)  low = mid+1;
                else high = mid;
            }
            if(nums[low]-nums[i]+vec[i]>=s && low-i+1<minLen) minLen = low-i+1;
        }
        
        if(minLen == numeric_limits<int>::max()) return 0;
        else return minLen;
    }
};

 

leetcode@ [209]Minimum Size Subarray Sum

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/4927820.html

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