Leetcode_80_Remove Duplicates from Sorted Array II

题目:
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

大概意思:有一个有序的数组nums, 经过处理之后数组中最多不会有三个重复的元素。返回值是新数组的长度。

思路
1.设置两个指针i,end. i指向的是数组的头。end指向数组的尾巴。
2.看看nums[i+2]是不是等于i,如果是的话(明显这个元素的个数大于两个)删除并且end–。如果不是i继续往前走。
3.返回是end+1
如图所示:
太简单,不用画图。
代码如下

    public int removeDuplicates(int[] nums) {
        if(nums.length==0)
            return 0;
        int i=0;
        int end=nums.length-1;
        while ((i+2)<=end){ //注意这个越界问题
            if(nums[i]==nums[i+2]){
                removeEle(nums,i+2);//把i+2给删除掉
                end--;//维护一下数组的长度
            }else {
                i++;//如果这个元素个数不大于3
            }
        }
        return end+1;
    }
    public void removeEle(int []nums,int index){
        for(int i=index;i<nums.length-1;i++){
            nums[i]=nums[i+1];
        }
    }

分析:这里使用了数组删除的操作比较费时间,不过整理来看思路比较简单。leetcode测试时间还是很快的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值