【Leetcode】从排序数组中删除重复元素

  • 题目:给定一个排序的数组,删除重复的位置,使每个元素只显示一次并返回新的长度

不要为另一个数组分配额外的空间,您必须使用常量内存来进行此操作。

例如,
给定输入数组nums = [1,1,2],

您的函数应返回长度= 2,与前两个元素NUMS是1和2分别

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.

//思路:遍历一遍数组
//用两个指针,当元素重复时,跳过重复的位置,当不重复的时候,把元素放到正确的位置上去
int removeDuplicates(vector<int>& nums)
{
    int temp = nums[0];
    int size = 0;
    for (int i = 0; i < nums.size();)
    {
        while (temp == nums[i])
        {
            i++;
        }
        if (size == 0)//为什么不直接从1开始,因为有可能元素个数为0,很可能造成数组越界,但是放在循环里面又需要每次进行判断,那有没有更优的解法呢?
        {
            size++;
        }
        if (size != i)
        {
            nums[size++] = nums[i++];
        }

    }
    return size;

}

几种更优的解法:
<一>

int removeDuplicates(vector<int>& nums) {
    int i = 0;
    for (int n : nums)
        if (!i || n > nums[i-1])
            nums[i++] = n;
    return i;
}

<二>

And to not need the !i check in the loop:

int removeDuplicates(vector<int>& nums) {
    int i = !nums.empty();
    for (int n : nums)
        if (n > nums[i-1])
            nums[i++] = n;
    return i;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值