Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
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<=2)
return n;
int pre = A[0];
int count = 1;
int pos = 1;
for(int i=1;i<n;i++)
{
if(A[i]==pre)
{
count++;
if(count<=2)
{
A[pos] = A[i];
pos++;
}
}
else
{
pre = A[i];
count = 0;
A[pos] = A[i];
pos++;
count++;
}
}
return pos;
}
No comments:
Post a Comment