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]
.
The basic idea is to have two pointers, p1 and p2, that go through the array. p2 runs faster and stops whenever it encounters a different value.
public class Solution {
public int removeDuplicates(int[] A) {
if(A.length == 0)
return 0;
int p1 = 0;
int end = A.length - 1;
int p2 = p1;
while(true){
if(p2 == A.length){
end = p1;
break;
}
if(A[p2] == A[p1]){
p2++;
}
else{
A[p1 + 1] = A[p2];
p1++;
}
}
return end + 1;
}
}