LeetCode | Minimum Size Subarray Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013033845/article/details/52390300

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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

还差一点没有想清楚,如何控制循环使得整个思路可以正常进行。

所想是start和end指针,当前比s小则继续往后取,比s大则需要更新minV,并且删除start之处元素。

而仅仅用if不能得到这样的判断,它会导致反复进入else子句,导致RE

<span style="white-space:pre">	</span>int start=0,end=0,sum=0,minV=INT_MAX;
        while(start<n){
            if(sum>=s){
                minV=min(minV,end-start);//计算最小值
                sum-=nums[start++];//去掉第一个数据,重新开始计数
            }
            else{
                sum+=nums[end++];//计算总量
                if(end==n && sum<s && minV==INT_MAX) return 0;
            }
        }
正确的方法是应用两个while循环

当获取到足够的数或者到达数组边界的时候,再对sum进行判断。

并且是循环到这个数据比s小。

这样就足以保证进入end++子句的判断中的时候,sum<s,进入start++子句的时候,sum>=s

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int n=nums.size();
        int start=0,end=0,sum=0,minV=INT_MAX;
        while(start<n && end<n){
            while(sum<s && end<n)
                sum+=nums[end++];//计算总量
            while(sum>=s && start<=end){
                minV=min(minV,end-start);//计算最小值
                sum-=nums[start++];//去掉第一个数据,重新开始计数
            }
        }
        return minV==INT_MAX?0:minV;
    }
};


猜你喜欢

转载自blog.csdn.net/u013033845/article/details/52390300