LeetCode 80. Remove Duplicates from Sorted Array II 删除排序数组中的重复项II(Java)

题目:

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:
Given 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 respectively.
It doesn’t matter what you leave beyond the returned length.

Example 2:
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn’t matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

解法:

解法一:

本题看似比较简单,但要注意题目中的要求,将删除重复项后的数组元素移至数组最前端。

思路为:
从数组第二个元素开始判断,用 count 记录数组中当前除去重复元素后的长度(即最终返回值),用 temp 记录连续出现重复数字的次数,若 nums[i] !== nums[i-1] 则 temp 重新置1,并通过 nums[count] = nums[i] 将有效的数字移至数组最前端。

class Solution {
    public int removeDuplicates (int[] nums) {
        if(nums.length == 0) {
            return nums.length;
        }
        int i = 1;
        int count = 1;
        int temp = 1;
        while(i<nums.length) {
            if(nums[i] == nums[i-1]) {
                temp++;
            } else {
                temp = 1;
            }
            if(temp <= 2) {
                nums[count] = nums[i];
                count++;
            }
            i++;
        }
        return count;
    }
}
解法一:

看到了他人一种更为简便的写法,解法如下:
其中 index 代表有效长度,且index 指向当前有效放置位置索引值 +1 的位置。通过nums[i] != nums[index - 2]判断是否已经有了两个重复的值,若没有则便是是有效数值,向前移动至 index 的位置,并将 index++

代码如下:

class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length <= 2) {
            return nums.length;
        }
        int index = 2;
        for(int i = 2; i < nums.length; i ++) {
            if(nums[i] != nums[index - 2])
                nums[index ++] = nums[i];
        }        
        return index;
    }
}

这种解法除了代码更简洁之外,扩展性也很强。比如题目若更改为,重读项最多可出现 n 次,则直接将上述代码中的 2 换成对应的数字 n 即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值