LeetCode #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.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]

Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

Follow up:

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

给定数组,找到一个子数组使得元素和大于等于目标值,并且长度最小。利用两个指针,一个表示起点,一个表示终点,当子数组合小于目标值,终点后移,当子数组和大于等于目标值,起点后移,并更新最小数组长度。

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int i=0;
        int j=0;
        int sum=0;
        int min_len=INT_MAX;
        while(i<nums.size()&&j<nums.size())
        {
            while(sum<s&&j<nums.size())
            {
                sum+=nums[j];
                j++;
            }
            while(sum>=s&&i<=j)
            {
                min_len=min(min_len,j-i);
                sum-=nums[i];
                i++;
            }
        }
        if(min_len==INT_MAX) return 0;
        else return min_len;
    }
};

猜你喜欢

转载自blog.csdn.net/lawfile/article/details/81175185