Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in 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]
.
1 public class Solution { 2 public int removeDuplicates(int[] A) { 3 int len = A.length; 4 if(len==0||len==1) 5 return len; 6 int p1=0,p2=1; 7 while(p2<len){ 8 if(A[p2]==A[p1]) 9 p2++; 10 else{ 11 p1++; //should p1++ first 12 A[p1] = A[p2]; 13 p2++; 14 } 15 } 16 return p1+1; //should p1+1 17 } 18 }