209. Minimum Size Subarray Sum解题报告

来源:互联网 发布:c语言左移和右移 编辑:程序博客网 时间:2024/06/05 04:02

题目

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;}
原创粉丝点击