Python双指针题型同向双指针滑动窗口
同向双指针可以被想象成一只蚯蚓:在不满足条件时,右指针(蚯蚓头)不断向前伸;满足条件时,右指针不动,左指针(蚯蚓尾)向前蠕动。模板是:end = 0 for start from 0 to (n-1): while end < n and (condition is not True): end += 1 if (condition is True): Process_start_and_endMinimum Size Subarray Sum
给定一个正整数数组 nums 和一个目标正整数,返回其和大于或等于 目标的 连续子数组的最小长度。如果没有这样的子数组,则返回 0。 class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: end, res, cursum = 0, sys.maxsize, 0 for start in range(len(nums)): while end < len(nums) and cursum < target: cursum += nums[end] end += 1 if cursum >= target: res = min(res, end - start) cursum -= nums[start] elif end == len(nums): break if res == math.inf: res = 0 return resLongest Substring Without Repeating Characters
定一个字符串 s ,找出最长的不重复字符的子串的长度。 class Solution: def lengthOfLongestSubstring(self, s: str) -> int: n, end, res = len(s), 0, 0 chars = [0] * 128 for start in range(n): while end < n and chars[ord(s[end])]==0: chars[ord(s[end])] = 1 end += 1 res = max(res, end - start) chars[ord(s[start])] = 0 if n - start < res: break return res