Minimum Size Subarray Sum - LeetCode 209

题目描述:
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.
click to show more practice.

More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Hide Tags Array Two Pointers Binary Search

分析:
要求给定和的连续序列的最短长度,需要标记首尾的下标。因此利用双指针,从前往后,用i标记连续序列最左边的下标,j标记最右边下标。
步骤:
1.两个指针初始化为0。j每移动一步,累加nums[j],如果当前的和小于目标和,那么继续右移j;若当前和不小于目标和,则更新最小长度,然后向右移动i,直到i和j之间的序列和小于目标和为止,每移动一次i,都得更新最小长度。

以下是C++实现代码:

/*///4ms///*/
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int size = nums.size();
        int minLen = size + 1; //最小长度不可能超过元素个数
        if(size == 0)
            return 0;
        int i = 0,j = 0;
        int sum = 0,len = 0;
        while(j < size)
        {
            sum += nums[j]; //累加右指针所指元素
            if(sum >= s )
            {
                while(sum >= s) //一直右移左指针,直到序列和小于目标值
                {
                    len = j - i + 1;
                    if(len < minLen) // 更新最小序列长度
                        minLen = len;
                    sum -= nums[i];  //更新序列和
                    i++; //右移左指针
                }             
            }
            j++;  //当前和小于目标值,则右移右指针
        }
        if(minLen > size)  //处理不存在符合要求的序列的情况
            return 0;
        return minLen;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值