Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear onlyonceand return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example, Given input arraynums=[1,1,2],

Your function should return length =2, with the first two elements of nums being1and2respectively. It doesn't matter what you leave beyond the new length.

two pointers

使用两个游标i和j来处理,i用来记录unique的并且帮助记录长度,j用来找不同的值。假设现在j = i + 1,如果A[i] == A[j],两值相同,那么我们递增j,跳过重复值,直到A[i] != A[j],这时候我们再设置A[i + 1] = A[j],是为了让非重复值A[j]放到A[i]后面,然后同时递增i和j,重复上述过程直到遍历结束。

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i = 0
        if len(nums) == 0:
            return 0
        for j in xrange(1, len(nums)):
            if nums[i] == nums[j]:
                continue
            else:
                nums[i+1] = nums[j]
                i += 1
        return i + 1

Last updated

Was this helpful?