---
# System prepended metadata

title: 0209. Minimum Size Subarray Sum
tags: [Leetcode, Sliding Window, Prefix Sum, Binary Search, Medium]

---

# 0209. Minimum Size Subarray Sum
###### tags: `Leetcode` `Medium` `Prefix Sum` `Sliding Window` `Binary Search`
Link: https://leetcode.com/problems/minimum-size-subarray-sum/
## 思路
### 思路一 Sliding Window $O(N)$ $O(1)$
### 思路二 Prefix Sum + Binary Search O(NlogN) O(N)
## Code
### 思路一
```java=
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int l=0, r=0, curr=0, ans=Integer.MAX_VALUE;
        while(r<nums.length){
            curr += nums[r];
            while(curr>=target){
                ans = Math.min(ans, r-l+1);
                curr -= nums[l++];
            }
            r++;
        }
        return ans==Integer.MAX_VALUE?0:ans;
    }
}
```
### 思路二
```java=
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int[] sum = new int[nums.length+1];
        for(int i = 0;i < nums.length;i++){
            sum[i+1] = sum[i]+nums[i];
        }
        int ans = Integer.MAX_VALUE;
        for(int i = 0;i < nums.length;i++){
            int lo = i+1;
            int hi = nums.length;
            while(lo<hi){
                int mid = (lo+hi)/2;
                if(sum[mid] < target+sum[i]){
                    lo = mid+1;
                }
                else{
                    hi = mid;
                }
            }
            if(sum[lo] >= target+sum[i]){
                ans = Math.min(ans, lo-i);
            }
            
        }
        if(ans == Integer.MAX_VALUE) return 0;
        return ans;
    }
}
```