Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
善用返回值!
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int lastInt = A[0]-1;
int lastIntTime = 0;
int length = 0;
for(int i=0;i<n;i++)
{
if(A[i]==lastInt)
{
lastIntTime ++;
}
else
{
lastIntTime = 1;
}
lastInt = A[i];
if(lastIntTime<3)
{
length++;
A[length-1] = A[i];
}
}
return length;
}
};
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]
.