Remove Duplicates from Sorted Array II [LeetCode]

时间:2023-03-08 21:13:39

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].

Solution:

     int removeDuplicates(int A[], int n) {
if(n <= )
return n;
int pre = A[];
int same_count = ;
int rm_count = ;
int i = ;
while(i < n - rm_count) {
if(A[i] == pre){
same_count ++;
}else{
pre = A[i];
same_count = ;
} if(same_count >= ){
//remove A[i]
for(int j = i + ; j < n - rm_count; j ++)
A[j - ] = A[j];
rm_count ++;
}else{
i ++;
}
}
return n - rm_count;
}