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]
.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if (n <= 2) return n; 5 int i, j, k = 1; 6 for (i = 0, j = 1; j < n; ++j) { 7 if (A[i] != A[j]) { 8 A[++i] = A[j]; 9 k = 1; 10 } else if (k == 1) { 11 A[++i] = A[j]; 12 ++k; 13 } 14 } 15 return i + 1; 16 } 17 };
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if (n <= 2) return n; 5 int i, j; 6 for (i = 1, j = 2; j < n; ++j) { 7 if (A[j] != A[i - 1]) { 8 A[++i] = A[j]; 9 } 10 } 11 return i + 1; 12 } 13 };