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]
.
public class Solution {
public int removeDuplicates(int[] A) {
int i,j=1,first = 0;//快慢指针,first判断是否是只重复一次。
if(A==null)return 0;
if(A.length<=1)return A.length;
for( i=1;i<A.length;i++){
if(A[i]!=A[i-1]){
A[j++]=A[i];
first=0;
}
else if(first==0){
A[j++]=A[i];
first=1;
}
}
return j;
}
}
public int removeDuplicates(int[] A) {
int i,j=1,first = 0;//快慢指针,first判断是否是只重复一次。
if(A==null)return 0;
if(A.length<=1)return A.length;
for( i=1;i<A.length;i++){
if(A[i]!=A[i-1]){
A[j++]=A[i];
first=0;
}
else if(first==0){
A[j++]=A[i];
first=1;
}
}
return j;
}
}
更简洁的:
public class Solution {
public int removeDuplicates(int[] A) {
int i,j=2;//快慢指针
if(A==null)return 0;
if(A.length<=2)return A.length;
for( i=2;i<A.length;i++){
if(A[i]!=A[j-2]) A[j++]=A[i];
}
return j;
}
}
public int removeDuplicates(int[] A) {
int i,j=2;//快慢指针
if(A==null)return 0;
if(A.length<=2)return A.length;
for( i=2;i<A.length;i++){
if(A[i]!=A[j-2]) A[j++]=A[i];
}
return j;
}
}