Simple Solution Two Pointers


  • 0
        public static int removeDuplicates(int[] A) {
    		if(A==null || A.length==0) return 0;
    		int p = 1;
    		for(int i=1;i<A.length;i++) if(A[i]!=A[i-1]) A[p++]=A[i];
    		return p;
    	}
    
    1. Pointer i scan the original array
    2. Pointer p points to the next position of the final array with no
      duplicates.
    3. At each loop if(A[i]!=A[i-1]) copy A[i] into A[p] and increase p;
    4. If (A[i]==A[i-1]) just skip this element increasing the pointer i for
      the original array. p remains the same in this case. The next unique element will be copied into this position.
    5. At the end you will have all unique elements in the first p
      positions, return p;

Log in to reply
 

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