[刷题防痴呆] 0209 - 长度最小的子数组

2022-01-28  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/minimum-size-subarray-sum/description/

题目描述

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 target, int[] nums) {
        int res = Integer.MAX_VALUE;
        int sum = 0;
        for (int left = 0, right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (left < nums.length && sum >= target) {
                res = Math.min(res, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }

        if (res == Integer.MAX_VALUE) {
            return 0;
        }
        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读