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 == 0) return 0;
unordered_map<int, int> hash;
int i = 0, j = 0;
while(j < n) {
if(hash[A[j]] == 0) {
hash[A[j]] = 1;
A[i++] = A[j++];
} else if(hash[A[j]] == 1) {
hash[A[j]] = 2;
A[i++] = A[j++];
} else if(hash[A[j]] == 2) {
j++;
}
}
return i;
}
};