leetcode 26. Remove Duplicates from Sorted Array 移除数组中的重复元素

本文详细解析了LeetCode26题“RemoveDuplicatesfromSortedArray”的两种解决方案,包括一种耗时较高的方法和一种时间复杂度为O(n)的高效算法。通过对比,突出了寻找不重复元素的技巧,避免了不必要的元素移动。

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

今日份leetcode 26. Remove Duplicates from Sorted Array
Description:
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:
Given 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 returned length.

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

这道题目是要将数组中重复的数去掉,只输出不重复的数。其实仔细想想这道题和前面做过的把指定的数移除 27. Remove Element 和把0后移 283. Move Zeroes 的题目的解题思想是一样的。当时智商下降没有想到…
我开始做的思路是:扫描数组,找到相同的数记录位置,接着往下找直到不再相同再记录另一个位置。然后把后面的元素统一往前移。循环下去。

class Solution {
    public int removeDuplicates(int[] nums) {
        int newlength = nums.length;        
        for(int i=0;i<nums.length-1;i++){
            if(nums[i]==nums[i+1])
                newlength--;  //记录数组中不重复元素的个数,最后用来输出
        }     
        for(int i=0;i<nums.length-1;i++){
            int a = i; //记录某个值的重复元素中,最后一个重复元素的位置,如{1,1,1,2,3}中的第三个1
            int b = i; //记录后面元素要往前移动到的位置
            while(nums[i]==nums[a+1]){
                a++;
                if(a+1>=nums.length)   //防止数组溢出
                    break;
            }
            for(int j=a+1;j<=nums.length-1;j++){  //往前移动
                nums[b+1]=nums[j];  
                b++;
            }            
        }       
        return newlength;
    }
}

这种方法耗时太高,131ms左右。
下面是一种更好的办法,找不相同的元素,用两个指针,一个用来记录不相同元素的索引位置,另一个用来记录要把不相同元素前移放入的位置(指针值连续)。这就是我上面所说的与leetcode 27,283相同的思路。都是从反面入手,找不相同的元素,而我是直接找相同的元素然后处理,这是比较麻烦的。唉唉,啥时候才能学以致用啊。。。

class Solution {
   public int removeDuplicates(int[] A) {
      if (A.length==0) return 0;
      int j=0;  //记录把不相同元素要往前移动的位置,从0开始连续的
      for (int i=0; i<A.length; i++)
          if (A[i]!=A[j]) A[++j]=A[i];
      return ++j;
   }
}

时间复杂度O(n),耗时大约7ms。

今天新学了一种酷酷的拍照新姿势,哈哈哈,没茅台!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值