title :
Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.
Do the allocate extra space for another array, and you must does this on 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]
.
code : OJ Test via runtime:143 ms
1 classSolution:2 #@param a list of integers3 #@return An integer4 defremoveduplicates (Self, A):5 ifLen (A) = =0:6 return07 8Curr =09 forIinchRange (0, Len (A)):Ten ifA[curr]! =A[i]: OneA[curr+1],a[i] = a[i],a[curr+1] ACurr + = 1 - returnCurr+1
Ideas :
First, exclude the special case with a length of 0
Using the double pointer technique: Use the Curr pointer to record the length of the data that does not contain duplicate elements; another pointer I go backwards
Tips: Note that Curr is the subscript of an array element starting with 0, so return to curr+1 when you finally return
Leetcode "Remove duplicates from Sorted Array" Python implementation