文章目录
- 移除元素
- 删除有序数组中的重复项
- 移动零
- 比较含退格的字符串
- 有序数组的平方
移除元素
双指针
删除指定项且不改变顺序
def removeElement(nums: list[int], val: int) -> int:
fast = slow = 0
while fast < len(nums):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
# 当 fast 指针遇到要删除的元素时停止赋值
# slow 指针停止移动, fast 指针继续前进
fast += 1
return slow
nums = [0,1,2,2,3,0,4,2,2,2]
val = 2
print(removeElement(nums,val))
删除有序数组中的重复项
删除重复项且不改变顺序
def removeDuplicates(nums: list[int]) -> int:
slow = 0
for fast in range(len(nums)):
if fast == 0:
nums[slow] = nums[fast]
slow += 1
if fast >= 1:
if nums[fast] != nums[fast - 1]:
nums[slow] = nums[fast]
slow += 1
return slow
nums = [1,1,2]
print(removeDuplicates(nums))
或者:
def removeDuplicates(nums: list[int]) -> int:
for i in range(len(nums) - 1, 0, -1):
if nums[i] == nums[i - 1]:
nums.pop(i)
return len(nums)
nums = [0,0,1,1,1,2,2,3,3,4]
print(removeDuplicates(nums))
移动零
和题一一样操作
def moveZeroes(nums: list[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
slow, fast = 0, 0
while fast < len(nums):
if nums[fast] != 0:
nums[slow] = nums[fast]
slow += 1
fast += 1
for i in range(slow,len(nums)):
nums[i] = 0
return nums
nums = [0,1,0,3,12]
print(moveZeroes(nums))
比较含退格的字符串
想不到
def backspaceCompare(s: str, t:str) -> bool:
i, j = len(s) - 1, len(t) - 1
skipS, skipT = 0, 0
while i >= 0 or j >= 0:
# S循环
while i >= 0:
if s[i] == '#':
skipS += 1
i -= 1
elif skipS > 0:
skipS -= 1
i -= 1
else:
break
# T循环
while j >= 0:
if t[j] == '#':
skipT += 1
j -= 1
elif skipT > 0:
skipT -= 1
j -= 1
else:
break
a = "" if i < 0 else s[i] # a[-1] = a,所以不能有负索引
b = "" if j < 0 else t[j]
if a != b:
return False
i -= 1
j -= 1
return True
s = "aaa###a"
t = "aaaa###a"
print(backspaceCompare(s,t))
有序数组的平方
正负数平方排序
def sortedSquares(nums: list[int]) -> list[int]:
for i in range(len(nums)):
nums[i] = nums[i] * nums[i]
nums.sort()
return nums
nums = [-4,-1,0,3,10]
print(sortedSquares(nums))
或者:
def sortedSquares(nums: list[int]) -> list[int]:
left = 0
right = len(nums) - 1
temp_lis = [-1] * len(nums)
site = len(nums) - 1
while left <= right:
if nums[left] ** 2 < nums[right] ** 2:
temp_lis[site] = nums[right] ** 2
right -= 1
else:
temp_lis[site] = nums[left] ** 2
left += 1
site -= 1
return temp_lis
nums = [-4,-1,0,3,10]
print(sortedSquares(nums))