【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) {
        if (nums.empty()) return 0;
        int n = nums.size();
        int left = 0, right = 0;
        int cur = nums[0];
        int res = (cur >= s ? 1 : INT_MAX);
        
        while (left <= right && right < n) {
            if (cur >= s) {
                res = min(res, right - left + 1);
                cur -= nums[left++];
            }
            if (right < n-1 && cur < s) {
                cur += nums[++right];
            }
            if (cur < s && right >= n-1) break;
        }
        
        return (res == INT_MAX ? 0 : res);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章