算法题目第一讲:双指针处理数组题目
解决力扣:
- [344. 反转字符串]
- [167. 两数之和 II - 输入有序数组]
- [26. 删除有序数组中的重复项]
- [27. 移除元素]
- [283. 移动零]
- [5. 最长回文子串]
配合b站视频讲解食用更佳:https://www.bilibili.com/video/BV1vW4y1P7V7
核心提示:好几道题是处理有序数组的!
适合人群:考研/复试/面试
解决痛点:1. 刷了就忘 2.换一道相似的题就不会
学完后会输出:对每类题目的框架
344.反转字符串
python
from typing import List
# @lc code=start
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left,right = 0, len(s)-1
while(left<right):
left_char = s[left]
right_char = s[right]
s[left] = right_char
s[right] = left_char
left+=1
right-=1
167:
有序数组,
python
from typing import List
# @lc code=start
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left,right = 0, len(numbers) - 1
while left < right:
# 因为有序,可以小了左指针向右移动
if numbers[left] + numbers[right] < target:
left += 1
# 大了右指针向左移动
elif numbers[left] + numbers[right] > target:
right-=1
# 注意题目要求的返回值从1开始编号
else:
return [left+1,right+1]
return [-1,-1]
# @lc code=end
26 删除有序数组中的重复元素
python
# @lc code=start
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# 空值则不用删除
if len(nums) == 0:
return 0
# 定义快慢指针
slow,fast = 0,0
# 只要快指针没越界,就继续往前走
while fast < len(nums):
if nums[fast]!=nums[slow]: # 不相等时慢指针需要+1
slow+=1
# 维护nums[0..slow]无重复
nums[slow] = nums[fast]
fast+=1
# 返回的是唯一值的个数,也就是slow+1
return slow+1
27.移除元素
python
from typing import List
# @lc code=start
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
fast,slow = 0,0
while fast<len(nums):
if nums[fast] !=val:
nums[slow] = nums[fast]
slow +=1
fast+=1
return slow
- 移动零
python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# step1:用快慢双指针把非0的按顺序排好
slow,fast = 0,0
while fast < len(nums):
if nums[fast]!=0:
nums[slow] = nums[fast]
slow+=1
fast+=1
# 最后几个补0操作 range是左闭右开的, 19行slow+1,所以不会覆盖
# 若全是0 则16行的while一次都没调用,全部补0, 从[0,len(nums)) 也是对的
for i in range(slow,len(nums)):
nums[i] = 0