title :
Follow up for "Remove duplicates":
What if duplicates is allowed at the most twice?
For example,
Given sorted Array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
code : OJ Test via runtime:120 ms
1 classSolution:2 #@param a a list of integers3 #@return An integer4 defremoveduplicates (Self, A):5 ifLen (A) < 3 :6 returnLen (A)7 8Pre =09Curr = 1Ten forIinchRange (2, Len (A)): One ifA[i] = = A[curr] andA[i] = =A[pre]: A Continue - Else: -A[curr+1],a[i] = a[i],a[curr+1] thePre + = 1 -Curr + = 1 - - returnCurr+1
Ideas :
First the length less than 3 can be returned directly, which saves a lot of things.
The main logic is: starting from the third element, whether the current element i is equal to the first two elements, if equal, I continue to go down, if not, then Exchange curr+1 and I position elements
Brush a few of the questions of the array, feeling there are some similar tricks, is to only traverse once, do not meet the conditions to exchange element position. Does not occupy additional space.
Leetcode "Remove duplicates from Sorted Array II" Python implementation