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

leetcode ---双指针+滑动窗口

时间:2015-06-06 16:37:38      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:leetcode   minimum size subarra   

一: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.

分析:一开始我采用的是LIS(longest increased sequence)中的最长递增子序列中的动态规划的思想,能通过,但是时间复杂度为O(N

^2);;;第二种方法是采用双指针+滑动窗口的思想,时间复杂度为O(N), 严格意义上说是2N,,比如 [1,2,3,15,3,4,5,15] s=14,,,只有在15处将前面的元素又重新加了一遍,故为2N

代码:

class Solution {
public:
   // 法一
    /*int minSubArrayLen(int s, vector<int>& nums) {
        int result = nums.size();
        bool flag = false;
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] >= s) return 1;
            int sum = nums[i];
            for(int j = i-1; j >= 0; j--){
                sum += nums[j];
                if(sum >= s){
                    result = min(result, i-j+1);
                    flag = true;
                    break;
                }
            }
        }
        if(flag)return result;
        return 0;
    }*/
    
    int minSubArrayLen(int s, vector<int>& nums) {     // 滑动窗口的形式+双指针
        int result = nums.size()+1;
        int frontPoint = 0, sum = 0;
        for(int i = 0; i < nums.size(); i++){
            sum += nums[i];
            while(sum >= s){
                result = min(result, i - frontPoint + 1);
                sum -= nums[frontPoint++];
            }
        }
        return result == (nums.size()+1) ? 0:result;
    }
};


leetcode ---双指针+滑动窗口

标签:leetcode   minimum size subarra   

原文地址:http://blog.csdn.net/lu597203933/article/details/46389491

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