defintersect(self, nums1: List[int], nums2: List[int]) -> List[int]: num_to_count = collections.Counter(nums1) res = [] for n in nums2: if n in num_to_count and num_to_count[n] > 0: num_to_count[n] -= 1 res.append(n) return res
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Implement the MovingAverage class:
MovingAverage(int size) Initializes the object with the size of the window size.
double next(int val) Returns the moving average of the last size values of the stream.
left is left pointer, i is right pointer 外循环为扩张,内循环为收缩。收缩条件为固定字符种数(必须固定或者少于k)或者(以及)固定字符频数。若字符种数不固定,要试1-26种字符,才能单调,详见L395
求最短串
Python代码:
1 2 3 4 5 6 7 8
deftwo_pointers(self, nums): for i inrange(len(nums)): <calculate condition such as char_to_count> while <meets condition>: res = min(res, i - left + 1) <求最短子列> <anti-calculate condition such as char_to_count> left += 1 return <result>
求最长串
Python代码:
1 2 3 4 5 6 7 8
deftwo_pointers(self, nums): for i inrange(len(nums)): <calculate condition such as char_to_count> while <does not meet condition>: <anti-calculate condition such as char_to_count> left += 1 res = max(res, i - left + 1) <求最短子列> return <result>