Week11 209. Minimum Size Subarray Sum

来源:互联网 发布:apache服务器配置 编辑:程序博客网 时间:2024/06/07 13:39

题目

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.

分析

题目的目的是为了找最短的子数组,所以我们应该先设定一个长度n,使得这个长度n的数组求和可以超过正整数s,于是以后遍历的时候,得到的数组长度最长只能是m。如果发现新的数组长度比n小,那么就更新数组长度m,使以后遍历的数组最长不能超过m,那么最后得到的m就是最短长度

代码

#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;}




原创粉丝点击