这道题跟Remove Duplicates from Sorted Array比較类似,差别仅仅是这里元素能够反复出现至多两次,而不是一次。事实上也比較简单。仅仅须要维护一个counter。当counter是2时,就直接跳过就可以,否则说明元素出现次数没有超,继续放入结果数组,若遇到新元素则重置counter。整体算法仅仅须要扫描一次数组,所以时间上是O(n),空间上仅仅须要维护一个index和counter,所以是O(1)。
代码例如以下:
public int removeDuplicates(int[] A) {if(A==null || A.length==0)return 0;int idx = 0;int count = 0;for(int i=0;i<A.length;i++){if(i>0 && A[i]==A[i-1]){count++;if(count>=3)continue;}else{count = 1;}A[idx++]=A[i];}return idx;
}
这样的简单数组操作的问题在电面中比較常见。既然简单,所以出手就要稳。不能出错,还是要保证无误哈。