卖萌的弱渣

I am stupid, I am hungry.

Remove Duplicates From Sorted Array

Remove Duplicates from Sorted Array

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

Note

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].

Solution

  • Two pointer start and i: one record next unduplicated position, the is used to tranverse the whole array
(Remove-Duplicates-from-Sorted-Array.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
    """
    @param A: a list of integers
    @return an integer
    """
    def removeDuplicates(self, A):
        # write your code here
        if A==None or len(A)==0:
            return 0
        start=0
        for i in range(len(A)):
            # find the non-duplicate element
            # update A[start+1]
            if A[i] != A[start]:
                start += 1
                A[start] = A[i]

        return start+1