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].
加入一个计数器,用于统计重复字符的个数。
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (!n) return 0;
int count = 1;
int idx = 0;
for (int i=1; i<n; i++) {
if (A[idx] == A[i]) {
++count;
if (count <= 2)
A[++idx] = A[i];
}
else {
A[++idx] = A[i];
count = 1;
}
}
return idx+1;
}
};Remove Duplicates from Sorted Array II -- leetcode
原文:http://blog.csdn.net/elton_xiao/article/details/45044215