題目:
Remove Duplicates from Sorted Array IIFollow 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]
.
思路:
前面是刪除重複所有的,這題是保留兩個,想當然的做了,結果沒考慮清楚,耗時不少。
C++ AC代碼:
class Solution {
public:
int removeDuplicates(int A[], int n) {
if( n < 3)
return n;
int i=0, j=1,cnt = 1;
for ( ; j<n; j++){
if( A[i] == A[j] ){
if ( cnt == 1 ){
A[++i]=A[j];
}
cnt++;
}
else{
A[++i] = A[j];
cnt = 1;
}
}
return i+1;
}
};