题目描述
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
样例
输入[1,1,2],返回删除重复元素后数组长度,2
输入[0,0,1,1,1,2,2,3,3,4],返回删除重复元素后数组长度,5
思路分析
构造一指针记录数组长度即可,无甚好说
代码
public int removeDuplicates(int[] A) {
if (A.length==0) return 0;
int j=0;
for (int i=0; i<A.length; i++)
if (A[i]!=A[j]) A[++j]=A[i];
return ++j;
}
结果