【LeetCode】80. Remove Duplicates from Sorted Array II

Problem:

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.

题目:给定一个有序数组,移除重复数值,使数组每个值最多出现两次。

不能额外申请数组空间,使用O(1)空间复杂度修改输入的数组。


思路:和之前做过一题类似,这题只不过规定了空间复杂度。使用O(1)复杂度,我们可以定义多个整型变量。

1.flag指向修改后数组的保留值的末尾。count计数末尾值出现次数。

2.当遇到与nums[flag]!=nums[i]不等时,count=1重新计数,

3.当count值小于3,即当前值出现为不超过两次,或者已遇到新值。将当前遍历nums[i]更新到保留数组值中,同时,flag、ret加一。

4.循环2-3,直到遍历结束。


扫描二维码关注公众号,回复: 2082411 查看本文章

代码1:

class Solution {
    public int removeDuplicates(int[] nums) {
        int len = nums.length;
        if(len<=2)
            return len;
        int ret = 1;
        int flag = 0;       
        int count=1;
        for(int i=1;i<len;i++){
            count++;
            if(nums[flag]!=nums[i])
                count=1;
            if(count<3){
                nums[++flag]=nums[i];
                ret++;
            }
        }
        return ret;
    }
}


此代码目前beats100%solution,且比submission中的最优solution好理解(个人理解)。

容小菜鸡贴图装一笔^_^

代码2:

class Solution {
    public int removeDuplicates(int[] nums) {
        int ret = 0;
        int len = nums.length;
        if(len<=2)//此判断可使运行时间更短
            return len;
        for(int i=0;i<len;i++){
            if(ret<2||nums[ret-2]<nums[i])
                nums[ret++]=nums[i];
        }
        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/hc1017/article/details/80163285
今日推荐