题目:
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;
}
};
运行时间 88ms