Title description
Example
Method: double pointer method
algorithm:
After the array is sorted, we can place two pointers i and j, where i is a slow pointer and j is a fast pointer. As long as nums[i] = nums[j], we increase j to skip duplicates.
When we encounter nums[j] != nums[i], the operation of skipping duplicates has ended, so we must copy the value of it (nums[j]) to nums[i+1]. Then increment i, and then we will repeat the same process again until j reaches the end of the array.
Code:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if nums is None:
return 0
i = 0
for j in range(1, len(nums)):
if nums[i] != nums[j]:
nums[i+1] = nums[j]
i += 1
return i + 1