Fast and simple inplace c++ soln (30ms)


  • 0
    R
    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            //two pointers fast and slow to keep track of duplicates
            int slow=0, fast=1, cnt=0; //counter counts how many are same
            if(n<=1)
                return n;
            while(fast<n) {
                if(A[fast] == A[slow]) {
                    cnt++;
    				if(cnt<2){ 
    					A[++slow] = A[fast]; //if less than 1 duplicate copy
    				}
                    fast++;				
                }
                else {	
                    //copy the fast pointer to slow pointer and move ahead both
                    A[++slow] = A[fast];
                    fast++;
                    cnt=0;
                }
            }
            return slow+1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.