class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# 头尾指针
i, j = 0, len(nums)
while i < j:
if nums[j - 1] == val:
# 尾指针命中,向前偏移
j -= 1
continue
if nums[i] == val:
# 头指针命中,交换头尾,并将尾指针向前,头指针向后偏移
nums[i], nums[j - 1] = nums[j - 1], nums[i]
j -= 1
i += 1
else:
# 未命中,头指针向后偏移
i += 1
# 切片截取
nums = nums[:j]
return j
1.2 面试经典150题-移除元素
于 2024-01-12 01:53:41 首次发布