Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
数组是排好序了的,如果当前元素不等于前两个元素,则把当前元素赋值到数组。
class Solution {
public:
int removeDuplicates(int A[], int n) {
int i,j=2;
if(n==0)return 0;
if(n==1)return 1;
for(i=2;i<n;i++)
if(A[i]!=A[j-2])A[j++]=A[i];//第一次时:j=2 然后j++,j变为3
return j
}
};