banner
cells

cells

为美好的世界献上 code

209. Minimum Size Subarray

209. Minimum Size Subarray Sum#

Given an array of positive integers nums and a positive integer target.

Find the minimal length of a contiguous subarray of which the sum ≥ target and return 0 if there is no such subarray.

Example 1:

Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the condition.

Example 2:

Input: target = 4, nums = [1,4,4]
Output: 1

Example 3:

Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0

Constraints:

  • 1<=target<=1091 <= target <= 10^9

  • 1<=nums.length<=1051 <= nums.length <= 10^5

  • 1<=nums[i]<=1051 <= nums[i] <= 10^5

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

Two Pointers#

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int n = nums.size();
        int i = 0, j = 0;
        int cur = 0;
        int res = INT_MAX;
        while (j < n) {
            cur += nums[j];
            while (cur >= target) {
                res = min(res, j - i + 1);
                cur -= nums[i];
                ++i;
            }
            ++j;
        }
        return res == INT_MAX ? 0 : res;
    }
};

Prefix Sum#

The sum of intervals should remind us of prefix sum.

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int n = nums.size();
        vector<int> prev(n + 1, 0);
        // prev[i] represents the sum of nums in the range [0, i)
        for (int i = 1; i <= n; ++i) {
            prev[i] = prev[i - 1] + nums[i - 1];
        }
        int res = INT_MAX;
        for (int i = 0; i < n; ++i) {
            // prev[j] - prev[i] represents the sum of nums in the range [i, j)
            // We need to satisfy prev[j] - prev[i] >= target
            // So prev[j] >= target + prev[i]
            int find_val = target + prev[i];
            // prev is non-decreasing, we can use binary search to find the right index of the range
            auto iter = lower_bound(prev.begin(), prev.end(), find_val);
            if (iter != prev.end()) {
                res = min(res, static_cast<int>(iter - prev.begin()) - i);
                // iter is 1 index ahead of the actual index we need (j is an open range), so no need to add 1
            }
        }
        return res == INT_MAX ? 0 : res;
    }
};
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.