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

本文介绍了一种不使用额外空间的方法来去除已排序数组中的重复元素,并保持元素的唯一性。通过两个指针p1和p2遍历数组,当遇到不同值时进行更新,最终返回新长度。
722

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



