LintCode 406: Minimum Size Subarray Sum (同向双指针经典题!!!)

  1. 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 -1 instead.

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.

Challenge
If you have figured out the O(nlog n) solution, try coding another solution of which the time complexity is O(n).

思路:同向双指针
注意:

  1. 凡是题目提到子串,子数组之类的,多考虑双指针(可能同向,也可能反向);
  2. 子串之类的题目有单调性,即超过某个就都满足
    左边不行右边行 - 最短子串, 如此题
    左边行右边不行 - 最长子串, 如Longest Substring Without Repeating Characters ???
  3. 同向双指针模板:右指针用for loop, 左指针嵌在for loop里面用while loop。满足条件时更新最大/小值,移动左指针并更新sum。
  4. 注意while loop的条件是 sum>=s,即==s的情况也必须考虑。LintCode 386的while loop也是一样。

代码如下:

class Solution {
public:
    /**
     * @param nums: an array of integers
     * @param s: An integer
     * @return: an integer representing the minimum size of subarray
     */
    int minimumSize(vector<int> &nums, int s) {
        int len = nums.size();
        if (len == 0) return -1;
        
        int left = 0;
        int minLen = INT_MAX;
        int sum = 0;
        
        for (int right = 0; right < len; ++right) {
            sum += nums[right];
            while (sum >= s) {  //注意这里是>=s,即==s的情况也考虑
                minLen = min(minLen, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
    
        return (minLen == INT_MAX) ? -1 : minLen;
    }
};

二刷:

class Solution {
public:
    /**
     * @param nums: an array of integers
     * @param s: An integer
     * @return: an integer representing the minimum size of subarray
     */
    int minimumSize(vector<int> &nums, int s) {
        int n = nums.size();
        int left = 0, right = 0;
        int sum = 0, res = INT_MAX;
        while (right < n) {
            sum += nums[right];
            right++;
            while (sum >= s) {
                res = min(res, right - left);
                sum -= nums[left];
                left++;
            }
        }
        return res == INT_MAX ? -1 : res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值