[LeetCode] Remove Duplicates from Sorted Array

本文介绍了一种在已排序数组中去除重复元素的方法,并提供两种解决方案:一种是通过简单的循环和索引操作来实现;另一种是利用STL库中的函数简化流程。这两种方法都不使用额外的空间。

前言

Remove Duplicates from Sorted Array是比较平易近人的一道题,做的时候直接模拟AC,后来在网上看到有STL做法,利用现成的函数和工具就是简便啊。


题目

题目链接

描述如下:

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.

大意就是已经排序好了的数组,不开新空间,把重复元素移除并返回处理后的新长度。要注意的是“It doesn't matter what you leave beyond the new length.”

思路

简单分析一下,思路就是一个循环再加一个索引,当检测到两元素不等,就写入。具体见代码。

代码

Solution 1:遍历移动

class Solution {
public:

    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0)
            return 0;
        else
        {
            int index = 0;
            int len = nums.size();
            for(int i = 0;i<len;i++)
            {
                if(nums[index] != nums[i])
                {
                    nums[++index] = nums[i];//当两个元素不等,向前挪动
                }
            }
            int ans = index + 1;
            return ans;//即去重后的数组长度
        }
    }
};

Solution 2:使用STL

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        return distance(nums.begin(),unique(nums.begin(),nums.end())); 
    }
};

补充

关于Unique()的说明,可参考这篇博文

此题能够使用Unique的一大原因是这是一个已排序数组,换句话说,如果有重复的多个元素,它们势必是相邻的。这就为使用unique提供了保证。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值