[leetcode]--26. Remove Duplicates from Sorted Array

本文介绍了一种在原地且常数内存使用的情况下去除有序数组中重复元素的方法,并提供了两种实现思路,包括遍历对比做标志位及一次遍历迭代。

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

Question 26:

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

中文解释:有一个有序的数组,里面有的数据出现了两次,其余的都只出现一次。删除这个些出现两次的数据之一,然后返回删除之后数组的长度。

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

解决思路:这里我提供两种解决思路,常规套路,第一种是最直观的思路,第二种是有点技巧的思路。

1)遍历对比做标志位

这里,以Integer.MAX_VALUE 作为标志,每当碰到重复的数据,就赋值成Integer.MAX_VALUE(这里其实是有一个bug的,如果整数数组中最后的数字是Integer.MAX_VALUE 这个时候就会有bug,虽然出现的概率很小),最后做一个遍历,删除所有值为Integer.MAX_VALUE的元素。

从上面的分析可知,时间开销接近2n,时间复杂度是O(n)。空间复杂度是O(1)。

public static int removeDuplicates(int[] nums) {
    int count=0;
    int result = nums.length;//标识数组最后的长度
    //以Integer.MAX_VALUE作为标志位
    int temp = Integer.MAX_VALUE;

    for(int i=0; i<nums.length-1; i++){
        if( (nums[i] ^ nums[i+1])==0 ){//存在相同的数字
            result--;
            nums[i] = temp;
        }
    }
    //遍历删除所有的Integer.MAX_VALUE
    for(int i=0; i<nums.length; i++){
        if(nums[i] == temp){
            count++;
        }else{
            nums[i-count] = nums[i];
        }
    }
    return result;
}

这种算法并不是什么好的算法。

2)一次遍历迭代

下面这种实现就只需要一次遍历,明显比前一种算法时间开销上节约了接近一半。

public static int removeDuplicates2(int[] nums) {
    /** 
    //注释部分和下面的逻辑是一模一样的,只是这里用for循环,下面的用foreach迭代。
    int index=0;
    for(int i=0; i<nums.length-1;i++){
        if(nums[i] == nums[i+1]){

        }else{
            nums[index++] = nums[i];
        }
    }
    nums[index++] = nums[nums.length-1];
    return index;*/
    //首先做一个判断,nums的长度是否为0,如果为0直接就返回0
    int i = nums.length > 0 ? 1 : 0;
    for (int n : nums)//迭代每个数据,然后判断
        if (n > nums[i - 1])
            nums[i++] = n;
    //返回数组长度
    return i;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值