Remove Duplicates from Sorted Array II
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].
很奇怪的题,和此题的第一代没有本质区别。
只要增加一个变量count记录当前已经出现的相同数字的个数。
如果count>2,不移动start,如果小于等于2,copy A[i] to A[start++]。
class Solution {
public:
int removeDuplicates(int A[], int n) {
int count = 1;
int start = 1;
int i = 1;
if(n == 0){
return 0;
}
while(i < n){
if(A[i] == A[i - 1]){
count++;
}
else{
count = 1;
}
if(count <= 2){
A[start++] = A[i];
}
i++;
}
return start;
}
};
