(1)思想:滑动窗口在字符串或者数组移动,直到末尾。
(2)作用:降低for循环嵌套的深度,通常情况下时间复杂度为O(N)
(3)注意:滑动窗口的长度可以动态变化,需要两个指针分别指向窗口的左边界和右边界。
(1)求数组中连续k数之和的最大值
方法一:暴力法(时间复杂度O(N2))
def getMaxSumkElements2(list, k):
"""
list:python中为列表类型
k:整数,默认k<=len(list)
"""
size = len(list)
maxsum = 0
for i in range(size-k+1): # 两层for循环嵌套,复杂度高
sum = 0
for j in range(i, i+k):
sum += list[j]
maxsum = max(maxsum, sum)
return maxsum
a = [-2,1,-3,4,-1,2,1,-5,4]
print(getMaxSumkElements2(a, 4))
6
def getMaxSumkElements(list, k):
"""
list:python中为列表类型
k:整数,默认k<=len(list)
"""
size = len(list)
sum = 0
maxsum = 0
for i in range(0, size): # 算法时间复杂度O(N)
if i < k:
sum += list[i]
else:
sum = sum + list[i] - list[i-k] # 核心代码
maxsum = max(maxsum, sum)
return maxsum
a = [-2,1,-3,4,-1,2,1,-5,4]
print(getMaxSumkElements(a, 4))
6
def lengthOfLongestSubstring(s):
position = {} # 字符和它的邻接索引的键值对
pre = 0 # pre窗口左界,i窗口右边界
maxlength = 0 # 最大子串长度
for i in range(len(s)):
if s[i] in position: # 如果和窗口内的重复
pre = max(pre, position[s[i]]) # 窗口左界更新
maxlength = max(maxlength, i - pre + 1) # 求最大子串
position[s[i]] = i + 1 #
return maxlength # 建立字符和它的邻接索引的键值对
s = "pwwkew"
print(lengthOfLongestSubstring(s))
ans:3