【LeetCode】解题80:Remove Duplicates from Sorted Array II

本文详细解析了LeetCode第80题“Remove Duplicates from Sorted Array II”的解决方案,介绍了一种使用双指针技术的高效算法,该算法可以在O(n)的时间复杂度和O(1)的空间复杂度下,将排序数组中重复出现超过两次的元素删除,并返回新的数组长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode解题 80:Remove Duplicates from Sorted Array II

Problem 80: Remove Duplicates from Sorted Array II [Medium]

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.

来源:LeetCode

解题思路

题解26:Remove Duplicates from Sorted Array类似,只是要把重复的频率上限改为2。

具体思路:

  • 使用一个指针index指向需要修改的位置,nums[0]~nums[index-1]代表已经检测过的未重复2次以上的数字。
  • 遍历数组,用last记录上一个数值的下标,跳过重复次数大于2的数字(即nums[i] == nums[last] && i - last > 1),将符合要求的数字填入nums[index],指针index向后移一位。
  • 数组个数小于3时直接返回。

时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( 1 ) O(1) O(1)

运行结果:

要点:双指针

Solution (Java)

class Solution {
    public int removeDuplicates(int[] nums) {
        int N = nums.length;
        if(N < 3) return N;
        int index = 1;
        int last = 0;
        for(int i = 1; i < N; i++){
            while(i < N && nums[i] == nums[last]){
                if(i - last < 2){
                    nums[index++] = nums[i];
                }
                i++;
            }
            if(i < N){
                last = i;
                nums[index++] = nums[i];
            }
        }
        return index;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值