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]
.
Have you met this question in a real interview?
思路:设置三个指针, 一个指向当前,一个slow, 一个 fast。 每次fast = slow + 1, A[slow] == A[fast] , fast 向后移动。
如果 fast - slow < 2, 只复制一个, 大于等于2 时候,复制俩, 然后 slow = fast , fast ++ 。
切忌, 最后要把剩余的 slow 全拷到 index。
易错点: 每个循环 slow = fast, fast++ ,fast 要初始化为 slow 的下一位。
public class Solution {
public int removeDuplicates(int[] A) {
int len = A.length;
if(len < 3)
return len;
int fast = 1;
int slow = 0;
int index = 0;
while(fast < len){
while(fast < len && A[fast] == A[slow]){
fast++;
}
if(fast - slow < 2){
A[index] = A[slow];
index++;
slow++;
}else{
A[index] = A[slow];
index++;
slow++;
A[index] = A[slow];
index++;
slow++;
}
slow = fast;//-----
fast++;//----
}
while(slow < len){//-----
A[index] = A[slow];
index++;
slow++;
}
return index;
}
}