209. Minimum Size Subarray Sum解题报告

题目

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous 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.

题目解析

题目大意是说给定一个数组,一个正整数s,找出最小连续的数组子集,使这个子集元素的和sum >= s, 如果这个数组所有元素的和比s小,则返回0

思路分析

因为是为了找最短的子数组,因此可以一开始设定一个长度n,使得这个长度n的数组求和可以超过正整数s,于是以后遍历的时候,得到的数组长度最长只能是n。如果发现新的数组长度比n小,那么就更新数组长度n’,使以后遍历的数组最长不能超过n’,那么最后得到的n’就是最短长度

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int _max = nums.size();
        if (_max == 0) return 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (i == 0) {
                int startmax = 0, result = 0, endpos = i;
                while (result < s && endpos < nums.size()) {
                    result += nums[endpos];
                    startmax++;
                    endpos++;
                }
                if (startmax < _max) _max = startmax;
                if (startmax == _max && result < s) return 0;
            } else {
                int addnum = _max, curaddnum = 1, result = nums[i];
                while (curaddnum <= addnum){
                    if (result >= s) {
                        if (curaddnum  <= _max) {
                            _max = curaddnum;
                            break;
                        }
                    }
                    if (i + curaddnum >= nums.size()) break;
                    result += nums[i + curaddnum++];
                }
            }
        }
        return _max;
    }
};
int main() {
    int iarray[]={1,2,3,4,5};
    size_t count=sizeof(iarray)/sizeof(int);
    vector<int> ivec3(iarray,iarray+count);
    Solution s;
    std::cout << s.minSubArrayLen(11, ivec3)<< std::endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值