码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 209. Minimum Size Subarray Sum_Medium

时间:2018-06-16 10:28:25      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:odi   complex   other   ons   you   class   time   and   ==   

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

标签:odi   complex   other   ons   you   class   time   and   ==   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9189709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!