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]
.
两个指针,一个指向老数组,一个指向新数组。代码如下:
public int removeDuplicates(int[] A) {
if (A == null || A.length < 2) {
return A.length;
}
int i = 1, j = 0;
while (i < A.length) {
if (A[j] != A[i]) {
A[++j] = A[i];
}
i++;
}
return j+1;
}