前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Minimum Size Subarray Sum — leetcode[通俗易懂]

Minimum Size Subarray Sum — leetcode[通俗易懂]

作者头像
全栈程序员站长
发布2022-07-10 13:27:41
4160
发布2022-07-10 13:27:41
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是全栈君。

题目描写叙述:

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.

意思是讲给定一组整数数组nums和一个数字s。求的nums数组中最短长度的连续数字和,使得该和大于等于s。 比方上面实例数组 2 。3。1,2,4,3这一个数组中,大于等于7的最短连续为 3 ,4 那么 minimal为2

解题思路

定义一个start 。表示序列的事实上点,初始值为0 定义一个tempresult,用来累积连续序列和,初始值为0 定义一个minlength,用来表示最短序列。初始值为INT-MAX

拿上面的数组列子进行解说nums= 2 ,3,1,2,4。3,s=7

首先 从2開始加,一直加到 2,3。1。2此时tempresult=8,大于等于7,先求的但当前minlength=4。然后缩短序列 start++,序列为3。1,2。对应的tempresult=6,小于7。则继续往后面累积和,3,1,2,4,然后缩短序列,变成,1,2,4,start++,此时minlength=3。然后继续缩短,2。4小于7,然后往后面继续累加,2,4,3,大于7,缩短,4,3,大于等于7,minlength=2。,到最后了。结束。

代码例如以下

代码语言:javascript
复制
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {


            int i,start,minlength,tempresult;

    minlength=INT_MAX;
    start=0;
    tempresult=0;
    for(i=start;i<nums.size();i++)
    {
        tempresult+=nums[i];

        if(tempresult>=s)
        {
            minlength=min(minlength,i-start+1);

            tempresult-=nums[start];
            start++;
            while(tempresult>=s)
            {

                minlength=min(minlength,i-start+1);
                tempresult-=nums[start];
                start++;
            }
        }


    }
    if(i-start==nums.size()&&tempresult<s)
        return 0;

    return minlength;
    }
};

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/115496.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年2月3,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档