LeetCode 80: Remove Duplicates from Sorted Array II

本文提供两种方法去除排序数组中的重复元素,并确保每个元素出现不超过两次。第一种方法利用了排序数组中相同元素相邻的特点;第二种方法则利用了数组的升序特性。

Notes:

For sorted array, there are two properties we can use:

1. All duplicates are stay togethers (First solution)

2. Ascending order (Second solution)

 

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length < 3) {
            return nums.length;
        }
        
        int start = 1;
        int prev = nums[0];
        boolean found = false;
        for (int i = 1; i < nums.length; i++) {
            if (prev == nums[i]) {
                if (found) {
                    continue;
                }
                found = true;
            } else {
                found = false;
            }
            nums[start++] = nums[i];
            prev = nums[i];
        }
        return start;
    }
}

 

 

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length < 3) {
            return nums.length;
        }
        
        int start = 0;
        for (int num : nums) {
            if (start < 2 || nums[start - 2] < num) {
                nums[start++] = num;
            }
        }
        return start;
    }
}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7469936.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值