前言
争取一天一道题目的进度。加油吧(
LeetCode 27.移除元素
提供三种方法:
方法一:快慢双指针
# 方法一:快慢双指针
fast,slow = 0,0
while fast < len(nums):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
还有另外一种写法:
# 法0
b = 0
for a in range(len(nums)):
if nums[a] != val:
nums[b] = nums[a]
b += 1
return b
方法二:对撞双指针(又叫交换移除)
# 方法二:对撞双指针/交换移除
right = len(nums)-1
left = 0
while left <= right:
if nums[left]==val and nums[right]!=val:
tmp = nums[left]
nums[left] = nums[right]
nums[right] = tmp
# 移动指针
if nums[left]!=val:
left += 1
if nums[right]==val:
right -= 1
return left
方法三:对撞双指针+覆盖
# 方法三:对撞+覆盖
right = len(nums)-1
left = 0
while left <= right:
if nums[left] == val:
nums[left] = nums[right]
right -= 1
else:
left += 1
return left
LeetCode 26.删除有序数组中的重复项
用快慢指针解决:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# 快慢指针
if not nums: #判空
return 0;
# i快指针,j慢指针
# i向前移动判断数和j是否相等,如果不同,j在下一个位更新这个数字
j = 0
for i in range(1, len(nums)):
if nums[i] != nums[j]: # 如果不同
j += 1 # 慢指针向前移
nums[j] = nums[i] # 使两指针数相同
return j + 1