classSolution(object): defminSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ # sliding widows ifnot nums: return0 l, r = 0, 0 minLength = len(nums)+1 res = 0 while r < len(nums): res += nums[r] r += 1 while res >= s: minLength = min(minLength, r - l) res -= nums[l] l += 1 return0if minLength == len(nums)+1else minLength
713. Subarray Product Less Than K
这道题甚至是上一道题的简略版本,要求出所有符合条件的。
1 2 3 4 5 6 7 8 9 10 11 12
classSolution(object): defnumSubarrayProductLessThanK(self, nums, k): if k <= 1: return0 prod = 1 ans = left = 0 for right, val inenumerate(nums): prod *= val while prod >= k: prod /= nums[left] left += 1 ans += right - left + 1 return ans
763. Partition Labels
简化版本的windows题
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defpartitionLabels(self, S): last = {c: i for i, c inenumerate(S)} j = anchor = 0 ans = [] for i, c inenumerate(S): # update j like a sliding window j = max(j, last[c]) if i == j: ans.append(i - anchor + 1) anchor = i + 1 return ans
from collections import deque classSolution(object): defmaxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ dq = deque() res = [] for i inrange(len(nums)): # limit range if dq and dq[0] == i-k: dq.popleft() while dq and nums[i] >= nums[dq[-1]]: # no meaning dq.pop() dq.append(i) if i - k + 1 >= 0: res.append(nums[dq[0]]) return res
76. Minimum Window Substring
这道题记录出现字母次数,然后知道windows里满足substring的时候再移动duplicate-- dic value maybe < 0