Leetcode One Question of the Day 2022.25 Question 26: Delete duplicates in the sorted array

Title description

Insert picture description here

Example

Insert picture description here
Insert picture description here

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

Guess you like

Origin blog.csdn.net/m0_51210480/article/details/114107669