Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Content:
Method: two pointers (slow and fast pointers)
Algorithm: same with P26
- 单独讨论长度为0,1,2的情况
- slow pointer从i = 1开始,fast pointer j = 2 to len(nums)
- if nums[j] != nums[i-1] 隔两个数比较,移动slow pointer i,将fast pointer 赋值
- 因为 pointers 是index,return i + 1
Code:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 3:
return len(nums)
else:
i = 1 #slow pointer
for j in range(2, len(nums)): #fast pointer
if nums[j] != nums[i-1]:
i += 1
nums[i] = nums[j]
return i+1
来源:CSDN
作者:湾区待时飞
链接:https://blog.csdn.net/weixin_44213218/article/details/103829462