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 in enumerate(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 in enumerate(S)} j = anchor = 0 ans = [] for i, c in enumerate(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
424. Longest Repeating Character Replacement
这道题的关键是最多可以替换k个字母,所以维护窗口的size是max出现字母的次数,剩下的都要替换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#from collections import defaultdict classSolution(object): defcharacterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """
count = {} max_count = start = result = 0 for end in range(len(s)): count[s[end]] = count.get(s[end], 0) + 1 max_count = max(max_count, count[s[end]]) if end - start + 1 - max_count > k: count[s[start]] -= 1 start += 1 result = max(result, end - start + 1) return result
567. Permutation in String
这道题是找Permutation in String,所以窗口size永远是end-start + 1,只要比较两个dict是否相同就可以了
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 in range(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