题目:
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]
.
代码:oj测试通过 Runtime: 143 ms
1 class Solution: 2 # @param a list of integers 3 # @return an integer 4 def removeDuplicates(self, A): 5 if len(A) == 0: 6 return 0 7 8 curr = 0 9 for i in range(0, len(A)): 10 if A[curr] != A[i] : 11 A[curr+1],A[i] = A[i],A[curr+1] 12 curr += 1 13 return curr+1
思路:
首先排除长度为0的special case
使用双指针技巧:用curr指针记录不含有重复元素的数据长度;另一个指针i从前往后走
Tips: 注意curr是数组元素的下标从0开始,所以再最后返回时要返回curr+1