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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=1) return n;
int i=0;
int j=1;
bool flag = false;
int temp = A[i];
while( j<n) {
if( A[j] != temp) {
i++;
A[i] = temp = A[j];
flag = false;
} else if( flag == false) {
i++;
A[i] = temp = A[j];
flag = true;
}
j++;
}
return i+1;
}
};
public class Solution {
//{}, {0}, {0,0} {0,1} {0,0,1,1,1, 3}
public int removeDuplicates(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
int sz = A.length;
if(sz<1) return 0;
boolean flag = false;
int i=0;
int j=1;
while(j<sz) {
if(A[j]==A[i]) {
if(!flag) {
A[++i] = A[j];
flag = true;
}
} else {
A[++i] = A[j];
flag = false;
}
++j;
}
return i+1;
}
}