[LeetCode] Remove Duplicates from Sorted Array

来源:互联网 发布:seo整站优化方案 编辑:程序博客网 时间:2024/06/06 17:06

前言

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提供了保证。







0 0