Monday, April 6, 2015

Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":
What if duplicates are allowed at 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].

Naive Thinking: At first I was considering using a hashmap, but that's taking O(n) space, definitely not efficient enough. It's definitely solvable in O(1) space.

 class Solution:  
   # @param A a list of integers  
   # @return an integer  
   def removeDuplicates(self, A):  
     fast = 0  
     slow = 0  
     while fast < len(A):  
       A[slow] = A[fast]  
       slow += 1  
       # when duplicate happens, go through all duplicates with current number  
       if fast+1 < len(A) and A[fast+1]==A[fast]:  
         A[slow] = A[fast+1]  
         slow += 1  
         i = 2  
         while fast+i < len(A) and A[fast+i] == A[fast]:  
           i += 1  
         fast += i  
       else:  
         fast += 1  
     return slow  

No comments:

Post a Comment