Remove Duplicates from Sorted Array II -- LeetCode

                原题链接:  http://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/  
这道题跟 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;}
这种简单数组操作的问题在电面中比较常见,既然简单,所以出手就要稳,不能出错,还是要保证无误哈。
           
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值