删除重复元素 -- 双指针

26. 删除有序数组中的重复项
80. 删除有序数组中的重复项 II


class RemoveDuplicates:
    def solution2(self, nums: List[int]) -> int:
        """
        26. 删除有序数组中的重复项
        https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
        :param nums:
        :return:
        """
        slow, fast = 0, 0

        while fast < len(nums):
            if nums[slow] != nums[fast]:
                slow += 1
                nums[slow] = nums[fast]
            fast += 1

        return slow + 1

    def solution2(self, nums: List[int]) -> int:
        """
        80. 删除有序数组中的重复项 II
        https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/description/
        :param nums: [1,1,1,2,2,3]
        :return: 5, nums = [1,1,2,2,3]
        """
        slow, fast = 0, 0
        n = len(nums)
        count = 0
        while fast < n:
            if nums[slow] != nums[fast]:
                slow += 1
                nums[slow] = nums[fast]
            elif slow < fast and count < 2:
                slow += 1
                nums[slow] = nums[fast]

            fast += 1
            count += 1

            if fast < len(nums) and nums[fast] != nums[fast-1]:
                count = 0

        return slow + 1


你可能感兴趣的:(LeetCode,数据结构与算法,双指针)