[Leetcode] Minimum Size Subarray Sum

来源:互联网 发布:网络电视直播翡翠台 编辑:程序博客网 时间:2024/05/17 06:46

描述

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.

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).

给定一个数组以及一个定值,求最小子数组长度,使得子数组的元素和大于等于这个定值。

分析

这道题可以使用双指针的方法,利用两个指针 left 以及 right 分别表示子数组的两端。让 right 指针右移直到指针到达数组末尾或者子数组满足条件,记录并更新子数组最小长度,之后 left 指针右移一位,重复上述操作,直到某个指针到达数组末尾。

代码

class Solution {public:    int minSubArrayLen(int s, vector<int>& nums) {        if (nums.empty()) return 0;        int left = 0, right = 0, sum = 0, res = INT_MAX;        while (right < nums.size()) {            while (right < nums.size() && sum < s) sum += nums[right++];            while (sum >= s) {                res = min(res, right - left);                sum -= nums[left++];            }        }        return res == INT_MAX ? 0 : res;    }};
0 0
原创粉丝点击