算法整理
滑动窗口思路,以下思路源自于此链接。
算法技巧的思路非常简单,就是维护一个窗口,不断滑动,然后更新答案么。LeetCode 上有起码 10 道运用滑动窗口算法的题目,难度都是中等和困难。该算法的大致逻辑如下:
int left = 0, right = 0;
while (right < s.size()) {`
// 增大窗口
window.add(s[right]);
right++;
while (window needs shrink) {
// 缩小窗口
window.remove(s[left]);
left++;
}
}
这个算法技巧的时间复杂度是 O(N),比字符串暴力算法要高效得多。
其实困扰大家的,不是算法的思路,而是各种细节问题。比如说如何向窗口中添加新元素,如何缩小窗口,在窗口滑动的哪个阶段更新结果。即便你明白了这些细节,也容易出 bug,找 bug 还不知道怎么找,真的挺让人心烦的。
所以今天我就写一套滑动窗口算法的代码框架,我连再哪里做输出 debug 都给你写好了,以后遇到相关的问题,你就默写出来如下框架然后改三个地方就行,还不会出 bug:
/* 滑动窗口算法框架 */
void slidingWindow(string s, string t) {
unordered_map<char, int> need, window;
for (char c : t) need[c]++;
int left = 0, right = 0;
int valid = 0;
while (right < s.size()) {
// c 是将移入窗口的字符
char c = s[right];
// 右移窗口
right++;
// 进行窗口内数据的一系列更新
...
/*** debug 输出的位置 ***/
printf("window: [%d, %d)\n", left, right);
/********************/
// 判断左侧窗口是否要收缩
while (window needs shrink) {
// d 是将移出窗口的字符
char d = s[left];
// 左移窗口
left++;
// 进行窗口内数据的一系列更新
...
}
}
}
其中两处 … 表示的更新窗口数据的地方,到时候你直接往里面填就行了。
而且,这两个 … 处的操作分别是右移和左移窗口更新操作,等会你会发现它们操作是完全对称的。
剑指 Offer 42. 连续子数组的最大和
# 执行效率更高
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
for i in range(1,len(nums)):
nums[i]+=max(nums[i-1],0)
return max(nums)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp=[nums[0]]
for i in range(1,len(nums)):
dp.append(max(nums[i],dp[i-1]+nums[i]))
return max(dp)
3. 无重复字符的最长子串
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
left=0
lookup=set()
n=len(s)
max_len,cur_len=0,0
for i in range(n):
cur_len+=1
while s[i] in lookup:
lookup.remove(s[left])
left+=1
cur_len-=1
if cur_len>max_len:max_len=cur_len
lookup.add(s[i])
return max_len
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
from collections import defaultdict
lookup=defaultdict(int)
start,end,max_len,counter=0,0,0,0
while end<len(s):
if lookup[s[end]]>0:
counter+=1
lookup[s[end]]+=1
end+=1
while counter>0:
if lookup[s[start]]>1:
counter-=1
lookup[s[start]]-=1
start+=1
max_len=max(max_len,end-start)
return max_len
209. 长度最小的子数组
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
ans = n + 1
for i in range(n):
total = 0
for j in range(i, n):
total += nums[j]
if total >= s:
ans = min(ans, j - i + 1)
break
return 0 if ans==n+1 else ans
# 模板法
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
if not nums:
return 0
n=len(nums)
total=0
min_len=float('inf')
start,end=0,0
while end<n:
total+=nums[end]
end+=1
while total>=s:
min_len=min(min_len,end-start)
total-=nums[start]
start+=1
return 0 if min_len==float('inf') else min_len
76. 最小覆盖子串
class Solution:
def minWindow(self, s: str, t: str) -> str:
from collections import defaultdict
lookup = defaultdict(int)
for c in t:
lookup[c] += 1
start = 0
end = 0
min_len = float("inf")
counter = len(t)
res = ""
while end < len(s):
if lookup[s[end]] > 0:
counter -= 1
lookup[s[end]] -= 1
end += 1
while counter == 0:
if min_len > end - start:
min_len = end - start
res = s[start:end]
if lookup[s[start]] == 0:
counter += 1
lookup[s[start]] += 1
start += 1
return res
239. 滑动窗口最大值
# 会超出时间限制 其中一种简单的方法
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
if n * k == 0:
return []
return [max(nums[i:i + k]) for i in range(n - k + 1)]