LeetCode OJ 26. Remove Duplicates from Sorted Array

本文介绍了一种在原地且常数内存使用的情况下去除已排序数组重复元素的方法。通过两个指针i和j,i用于遍历整个数组,而j则记录不重复元素的最新位置。当遇到新的不重复元素时,将其移动到j所指向的位置。

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

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.

Subscribe to see which companies asked this question

【思路】

1. 举个例子[1,1,1,2,2,2,3,4,5],我的想法就是找到每一节重复数字的长度,然后把后面的数字向前移动,直到遍历到数组最后。

上述例子中,我们从头开始发现有1重复出现了3次,因此我们把1后面的数字向前移动2,变为[1,2,2,2,3,4,5],然后把数组的len变为len-2,重复上面的结果直到遍历到最后。但是这个方法的效率并不高,每发现一个重复的元素都要把后面的数字向前移动,有没有更好的思路呢?

2. 一个更好的方法是:我们维持两个变量,i 用来遍历数组,j 用来指示数组中不重复的那部分的最后一个值的下标。在遍历数组的过程中,如果当前值和前一个值不同,则nums[++j] = nums[i],否则的话继续向前遍历。形象化的过程如下:

  • j = 0; i = 1;

  • nums[i] 等于 nums[i-1];

  • nums[i] 不等于 nums[i-1]; nums[++j] = nums[i];

  • 省略若干步


【java代码1】

 1 public class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if(nums==null || nums.length==0) return 0;
 4         int len = nums.length;
 5         int duplen = 0;
 6         for(int i = 0; i < len - 1; i++){
 7             duplen = 0;
 8             for(int j = i + 1; j < len; j++){
 9                 if(nums[j] == nums[i]) duplen++;
10                 else break;
11             }
12             if(duplen > 0){
13                 for(int k = i + duplen + 1; k < len; k++){
14                     nums[k-duplen] = nums[k];
15                 }
16                 len = len - duplen;
17             }
18         }
19         return len;
20     }
21 }

 【java代码2】

 1 public class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         if (nums.length == 0)
 4             return 0;
 5         int j = 0;
 6         for(int i=1; i<nums.length; i++) {
 7         if (nums[i-1] != nums[i])
 8             nums[++j] = nums[i];
 9         }
10         return j;
11     }
12 }

 

转载于:https://www.cnblogs.com/liujinhong/p/5510663.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值