Remove Duplicates from Sorted Array

Question

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

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

Example Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

Thoughts

双指针,index loop原 array, size是新的array的指针,只存distint value

Solution

class Solution:
    """
    @param A: a list of integers
    @return an integer
    """
    def removeDuplicates(self, A):
        # write your code here
        if not A:  
            return 0     
        size = 1         
        index = 1  
        while index < len(A):     
            if A[index] == A[index-1]:
                index += 1
            else:  
                A[size] = A[index]
                size += 1
                index += 1
        return size