26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array 从一个排序的数组中删除重复的元素,要求不能使用额外的内存

解题思路

input: nums = 1

init: length=1, slow=0, fast=1
1. fast == length, nums = 1
2. return slow + 1 = 1


input: nums = 1 1

init: length=2, slow=0, fast=1
1. fast < length, , nums[slow] == nums[fast], slow + 0 -> 0, fast + 1 -> 2, nums = 1 1
2. fast == length, nums = 1 1
3. return slow + 1 = 1



input: nums = 1 1 2

init: length=3, slow=0, fast=1
7. fast < length, nums[slow] == nums[fast], slow + 0 -> 0, fast + 1 -> 2, nums = 1 1 2
8. fast < length, nums[slow] != nums[fast], slow + 1 -> 1, fast + 0 -> 2, nums[slow] = nums[fast], nums = 1 2 2
9. fast < length, nums[slow] == nums[fast], slow + 0 -> 1, fast + 1 -> 3, nums = 1 2 2
10. fast == length
11. return slow + 1 = 2

python3 实现

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)
        slow = 0
        fast = 1
        while fast < length:
            if nums[slow] == nums[fast]:
                fast += 1
            else:
                slow += 1
                nums[slow] = nums[fast]
        return slow + 1

你可能感兴趣的:(LeetCode)