KK's blog

每天积累多一些

0%

Two Pointers

算法思路:

left is left pointer, i is right pointer

求最短串

Python代码:

1
2
3
4
5
6
7
8
def two_pointers(self, nums):
for i in range(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
def two_pointers(self, nums):
for i in range(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>

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview