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.

题目思路,因为数组已经是排序数组,所以我们只需要考虑让每个元素的重复个数限制在2以内即可,使用一个标志来标识。首先想到的最简单的思路应该是使用map来标记每个数的出现次数,大于2时不再进行操作,2以内的则对数组相应元素进行赋值。代码入下:

    public int removeDuplicates(int[] nums) {
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<nums.length; i++){
            if(!map.containsKey(nums[i])) {
                nums[count] = nums[i];
                map.put(nums[i], 1);
                count++;
            }else if(map.get(nums[i]) == 1) {
                nums[count] = nums[i];
                map.put(nums[i], map.get(nums[i]) + 1);
                count++;
            }
        }
        return count;
    }

这种方法因为使用了hashmap导致算法效率较低,我们考虑能不能仅使用一个标记来依次表示所有数字出现次数,就有了下面的代码,使用一个boolean型的flag标志前后相邻数字是否相等:

    public static int removeDuplicates1(int[] nums){
        if(nums.length<=1)
            return nums.length;
        int count = 1;
        boolean flag = false;
        for(int i=1; i<nums.length; i++){
            if(nums[i] == nums[i-1] && !flag){
                nums[count] = nums[i];
                count++;
                flag = true;
            }else if(nums[i] != nums[i-1]){
                nums[count] = nums[i];
                count++;
                flag = false;
            }
        }
        return count;
    }

另外,在discuss中看到了一种极其简洁的代码,如下所示,很6:

    public int removeDuplicates2(int[] nums) {
        int i = 0;
        for (int n : nums)
            if (i < 2 || n > nums[i-2])
                nums[i++] = n;
        return i;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值