problem:
Follow up for "Remove Duplicates":What if duplicates are allowed at mosttwice?
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].
Hide Tags
ArrayTwo Pointers
题意:对数组进行去重操作,同一元素最多出现2次,,返回新数组大小,同时更新数组。
thinking:
(1)先对数组排序
(2)从左往右遍历数组,出现相同元素开始计数,当重复出现次数超过2次时,用后面的元素覆盖多出的元素(数组往前移动)。
code:
class Solution {public:int removeDuplicates(int A[], int n) {if(n<3)return n;int i=0;int j=0;sort(A,A+n);while(j<n){while(j<n&&A[j]==A[++j]); //J定位到最后一个相同元素的下一个位置if(j-i>2){int num=j-i-2; //多余的元素的个数for(int k=0;k<n-j;k++) //往左移动覆盖多余的元素A[i+2+k]=A[j+k];j=i+2; //更新jn-=num; //数组减小num}i=j; //更新i}return n;}};
当我要取的时候,你淘气的躲开了,