[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

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9189709.html
今日推荐