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].
题目含义:在有序表中将重复的元素去掉,并返回新的长度。
题目思路:采用两个指针,i(从1开始)和j(从i+1开始,小于n),如果A[i-1]!=A[j],令A[i]=A[j],接下来i++,j++
解题代码:
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n==0||n==1)
return n;
int i,j;
for(i=1,j=1;j<n;j++){
if(A[i-1]!=A[j]){
A[i]=A[j];
i++;
}
}
return i;
}
};