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]
.
移除数组中重复次数超过2次以上出现的数,但是可以允许重复2次。
这个题类似Remove Duplicates from Sorted Array,第一个想法很直接就是计数,超过2次的就忽略,依据这个思路的代码见代码一;
上面的思路可行,但是代码看着比较冗余,判断比较多。再来想想原来的数组,该数组是排好序的,如果一个数出现3次以上,那么必有A[i] == A[i-2]。所以根据这个关系可以写出比较精简的代码二。详见代码。
class Solution { public: int removeDuplicates(int A[], int n) { if(A==NULL || n<=0) return 0; int start=1, count = 1, back = A[0]; for(int i=1; i<n; ++i){ if(count<2){ A[start++] = A[i]; if(back != A[i]){ back = A[i]; count = 1; }else{ ++count; } }else{ if(A[i] != back){ count = 1; A[start++] = A[i]; back = A[i]; }else{ ++count; } } } return start; } };
class Solution { public: int removeDuplicates(int A[], int n) { if(A==NULL || n<=0) return 0; if(n==1) return 1; int start=1,back = A[1]; for(int i=2; i<n; ++i){ if(A[i] != A[i-2]){ A[start++] = back; back = A[i]; } } A[start++] = back; return start; } };
[LeetCode] Remove Duplicates from Sorted Array II [27],布布扣,bubuko.com
[LeetCode] Remove Duplicates from Sorted Array II [27]
原文地址:http://blog.csdn.net/swagle/article/details/29822565