方法一、双指针
判断nums
的长度是否为0,为0则不包含任何元素,因此返回0。当数组nums
的长度大于0时,数组中此时至少包含一个元素,在删除重复元素之后也至少剩下一个元素,因此nums[0]
保持原状即可,从下标1开始删除重复元素。
定义两个指针fast
和slow
分别为快指针和慢指针,快指针则遍历数组到达下标的位置,慢指针表示下一个不同元素要填入的下标位置,初始时两个指针都指向下标sums[1]
Python3 代码题解
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
fast = slow = 1
while fast < n:
if nums[fast] != nums[fast - 1]:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
![](https://blog.liuyingjie.com.cn/wp-content/uploads/2023/07/26.-删除有序数组中的重复项.png)
Source: LeetCode(The title reproduced in this blog is for personal study use only)
Be First to Comment