Leetcode.209 | Minimum Size Subarray Sum
阿新 • • 發佈:2020-08-07
Leetcode.209 Minimum Size Subarray Sum
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).
Solution
1. 滑動視窗
- 時間複雜度:\(O(n)\)
- 空間複雜度:\(O(1)\)
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: n = len(nums) # 判斷為空的時候 if n == 0: return 0 # res:(1)記錄結果值 (2)處理沒有結果時的情況 res = n+1 l = 0 r = 0 su = nums[l] while l < n: if su >= s: res = min(r - l + 1, res) su -= nums[l] l += 1 elif r < n-1: r += 1 su += nums[r] else: break if res == n+1: return 0 return res
2. 二分查詢法
主要思路:利用二分法查詢符合條件的框最小尺寸
相當於在\([l,r]\)中查詢size位置,滿足條件,最後得到的\(size+1\)才是真正的尺寸
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: l = 0 r = len(nums) - 1 res = 0 while l <= r: size = l + (r - l)//2 if self._find_aim(s, nums, size): r = size-1 res = size + 1 else: l = size+1 return 0 if res == 0 else res def _find_aim(self,s,nums,size): sum = 0 for i in range(len(nums)): sum += nums[i] if i > size: sum -= nums[i-size-1] if sum >= s: return True return False