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]
.
Better Approach
Key to solve:
start from index: prev=1; curr=2 since allow twice duplication;
There are comparison cases:
1:Only twice duplication allow: compare with two prior elements:
2. Not accepted case.
Check coding in detail below
public class Solution {
public int removeDuplicates(int[] A) {
int len=A.length;
if(len<3) return len;
int prev=1;
int cur=2;
while(cur<len){
//accepted case
if(A[cur]==A[prev] && A[cur]==A[prev-1]){
cur++;
}else{ //unaccepted case
prev++;
A[prev]=A[cur];
cur++;
}
}
return prev+1;
}
}