Problem: 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.

For example,
Given input array A = [1,1,2],

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

Solution: Remove Duplicates from Sorted Array, Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-01-01 22:37:45
# @Author : NSSimacer
# @Version : 1.0
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if len(A) == 0:
return 0
index = 0
for i in xrange(1, len(A)):
if A[i] != A[index]:
index += 1
A[index] = A[i]
return index + 1

时间复杂度O(n),空间复杂度O(1)。