Remove Duplicates from Sorted Array

本文详细介绍了如何在不使用额外空间的情况下,通过遍历排序数组来移除重复元素,并返回处理后的数组长度。通过定义变量i和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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
中文:
给一个排序的数组,移除掉重复的元素,让每个元素只出现一次,然后返回新的长度。
注意必要分配给数组额外的空间,必须存放在固定的内存

分析:定义i,j表示数组的位置。
如果j指向的数组与i指向的数据重复,则j移动到下一个位置。
如果指向的值不重复,则将i+1,数据移动到i+1,j继续增加。

class Solution {
public:
   int removeDuplicates(vector<int>& nums) {
       int n=nums.size();
       int i,j,k;
       if(n==0)
       return 0;
       i=0;j=1;
       for(k=1;k<n;++k)
       {
           if(nums[i]!=nums[j])
           {
               i++;
               nums[i]=nums[j];
               j++;
           }
           else
           j++;
       }
       return i+1;
   }
};

Runtime: 32 ms
注意
1.首先要判断这个数组是否为空,如果为空的话,情况特殊。
注意对边界情况要考虑清楚。
2.另外多定义了一个数据k,多占用了一个空间,可以省略这个k,用j当做循环就可以了。可以做一些改进。

c语言版本

int removeDuplicates(int* nums, int numsSize) {
    if(numsSize==0)
    return 0;
    int i,j;
    i=0;
    for(j=1;j<numsSize;++j)
    {if(nums[i]!=nums[j])
    nums[++i]=nums[j];
    }
    return i+1;
}

Runtime: 16 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值