# 209. Minimum Size Subarray Sum

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

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

> 内容描述

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

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

双指针走起，beats 98.40%

```python
class Solution(object):
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        start, end, sums, res = 0, 0, 0, sys.maxsize
        while end < len(nums):
            sums += nums[end]
            end += 1
            while sums >= s:
                sums -= nums[start]
                start += 1
                res = min(res, end-start+1)
        return res if res != sys.maxsize else 0
```


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

> 思路 1
******- 时间复杂度: O(NlgN)******- 空间复杂度: O(N)******

思路参考[Approach #3](https://leetcode.com/problems/minimum-size-subarray-sum/solution/)

```python
from bisect import bisect_left
class Solution(object):
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        res = sys.maxsize
        sums = [0] * (len(nums)+1)
        for i in range(1, len(nums)+1):
            sums[i] = sums[i-1] + nums[i-1] # Sum of first i elements
        for i in range(1, len(nums)+1):
            to_find = s + sums[i-1] # minimum subarray starting from index i to have sum greater than s
            idx = bisect_left(sums, to_find)
            if idx != len(sums):
                res = min(res, idx-i+1)
        return res if res != sys.maxsize else 0
```
