Leetcode 26. Remove Duplicates from Sorted Array

Description: Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Link: 26. Remove Duplicates from Sorted Array

Examples:

Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 
It doesn't matter what you leave beyond the returned length. Example 2: Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4] Explanation: Your function should return length = 5, with the first five elements of nums being modified to
0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.

 

思路: 删除有序数组中的重复元素,返回长度。记录前一个元素的值,如何当前与之相同,就删除当前元素,否则更新前一个元素和长度。

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 1: return len(nums)
        i, pre = 1, nums[0]
        while nums[i:]:
            if nums[i] == pre:
                nums.pop(i)
            else:
                pre = nums[i]
                i += 1
        return i

但似乎不需要物理删除,只要内部调整位置就可。两个指针,left指向要替换的位置,right指向要替换的数。

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n <= 1: return n
        left, right = 0, 1
        while right < n:
            while right < n and nums[left] == nums[right]:
                right += 1
            left += 1
            if right < n:
                nums[left] = nums[right]
        return left

日期: 2021-04-06  好运会来吗?

posted @ 2021-04-06 20:22  summer_mimi  阅读(48)  评论(0编辑  收藏  举报