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]
.
这个很容易判断了,设两个index,一个是遍历的,一个是指向返回的最后位置,因为已经排序了,所以判断索引的值与最后位置及前一个的值是否相等,相等继续遍历,不相等更新索引。
1 #include <iostream> 2 using namespace std; 3 4 class Solution { 5 public: 6 int removeDuplicates(int A[], int n) { 7 if(n<3) return n; 8 // cout<<n<<endl; 9 int retidx= 1,curidx =2; 10 for(;curidx<n;curidx++){ 11 // cout<<retidx<<" "<<curidx<<endl; 12 if(A[retidx]==A[curidx]&&A[retidx-1]==A[curidx]) 13 continue; 14 A[++retidx] = A[curidx]; 15 } 16 return retidx+1; 17 } 18 }; 19 20 int main() 21 { 22 int a[]={}; 23 Solution sol; 24 int ret = sol.removeDuplicates(a,sizeof(a)/sizeof(int)); 25 for(int i=0;i<ret;i++) 26 cout<<a[i]<<" "; 27 cout<<endl; 28 return 0; 29 }