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]
.
这道题让删除重复元素,所以方法是定义一个index,然后A[index]=A[i]; 即可。
public int removeDuplicates(int[] A) {
if (A == null || A.length == 0)
return 0;
int index = 1;
for (int i = 1; i < A.length; i++) {
if (A[i] == A[i - 1])
continue;
else
A[index++] = A[i];
}
return index;
}
目标是把A[index]=A[i]; 也就是说A[index]是合法位置,要把数组里的每个元素都放在里面。
如果不合法,continue,合法,放进去就可以了。
最后不要忘记了index++。