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;
}

本文介绍了一种不使用额外空间的方法来去除已排序数组中的重复元素,并保持元素出现次数不超过一次。通过双指针技巧实现,其中一个指针指向新数组位置,另一个遍历原始数组。
253

被折叠的 条评论
为什么被折叠?



