Leetcode Minimum Size Subarray Sum

Leetcode Minimum Size Subarray Sum ,本算法主要通过两个游标记录求和的范围,并不断移动end游标,如果和大于s,则移动begin游标,从而缩紧约束,同时不断记录当前求和范围长度,相关cpp代码以及测试如下:

#include<iostream>
#include<vector>
#include<climits>

// The basic method fo this algorithm is that we record the begin and end index
// of some subarray, and increase the end index of the subarray each time.
// We check the sum of the subarray after we increace the end index, if the
// summary of the subarray is greater than s, we just increase the begin index
// to decrease the member of the subarray until the threshold value.
// We compare the (end - begin + 1) with current minimal length.
// Do these until end arrive the end of the nums.
using namespace std;
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        // If the array is empty, just return 0.
        if (nums.size() == 0) {
            return 0;
        }
        int begin = 0;
        int end = 0;
        int sum = 0;
        int len = nums.size();
        int min = INT_MAX;
        for (; end < len; end ++) {
            sum += nums[end];
            // Decrease the summary to the threshold.
            while (sum - nums[begin] >= s) {
                sum -= nums[begin];
                begin ++;
            }
            // Update the minimal length if necessary.
            if (sum >= s && end - begin + 1 < min) {
                min = end - begin + 1;
            }
        }
        return min < INT_MAX? min: 0;
    }
};

// Sample:
// input: ./a.out 7 2 3 1 2 4 3
// output: result: 2
int main(int argc, char* argv[]) {
    Solution so;
    vector<int> test;
    for (int i = 2; i < argc; i ++) {
        test.push_back(atoi(argv[i]));
    }
    int re = so.minSubArrayLen(atoi(argv[1]), test);
    cout<<"result: "<<re<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值