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]
.
分析:从第三个数开始,每个数都只和它前面第二个数相比较,如果不同的话,则在结果中添加该数;如果相同,则不处理。运行时间21ms
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if(n <= 2) return n; 5 6 int index = 2; 7 for(int i = 2; i < n; i++){ 8 if(A[i] != A[index-2]) A[index++] = A[i]; 9 } 10 return index; 11 } 12 };