[LeetCode] 209. Minimum Size Subarray Sum_Medium

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 209. Minimum Size Subarray Sum_Medium相关的知识,希望对你有一定的参考价值。

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 class Solution:
 2     def minSubArrayLen(self, mins, nums):
 3         """
 4         :type s: int
 5         :type nums: List[int]
 6         :rtype: int
 7         """
 8         if not nums: return 0
 9         l, r, s, m = 0, 0, 0, None
10         while r < len(nums):
11             s += nums[r]
12             r += 1
13             while s >= mins:
14                 m = r - l if not m else min(m, r-l)
15                 s -= nums[l]
16                 l += 1
17         return m if m else 0

我自己最开始的solution想的是用Two Pointers, l = 0, r = len(nums) -1, 然后分别往中间扫, 但是pass不了所有的test cases, 不知道问题出在哪. 

 

 1         # myself solution, but can not pass all the test cases
 2         
 3         if not nums: return 0
 4         l, r, ans = 0, len(nums)-1, 0
 5         while l<= r and sum(nums[l:r+1]) >= s:
 6             ans = r-l +1
 7             #print(nums[l:r+1])
 8             if nums[l] < nums[r]:
 9                 l += 1
10             elif nums[l] > nums[r]:
11                 r -= 1
12             else:
13                 templ, tempr = l+1, r-1
14                 condition = True
15                 while(templ <= tempr and condition):
16                     if nums[templ] == nums[tempr]:
17                         templ += 1
18                         tempr -= 1
19                     elif nums[templ] < nums[tempr]:
20                         l += 1
21                         condition = False
22                     else:
23                         r -= 1
24                         condition = False
25                 if condition:
26                     l += 1
27         return ans

 

以上是关于[LeetCode] 209. Minimum Size Subarray Sum_Medium的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 209. Minimum Size Subarray Sum

刷题-LeetCode209. Minimum Size Subarray Sum

LeetCode-209 Minimum Size Subarray Sum

[LeetCode] 209. Minimum Size Subarray Sum_Medium

LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题

[LeetCode] 209. Minimum Size Subarray Sum 最短子数组之和