leetcode-26&80 Remove Duplicates from Sorted Array I&II

来源:互联网 发布:淘宝虚拟资源网 编辑:程序博客网 时间:2024/06/07 09:09

26.
题干:
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.

题目简单,只需要一个迭代器进行判断相邻两个值是否相等,如果相等删除一个即可。
注意:对于迭代器的删除操作一定小心,迭代器增减的位置,以及由于增减操作造成的迭代器失效的问题;注意判断vector是否为空;

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.begin() != nums.end())        for(vector<int>::iterator itr= nums.begin()+1; itr != nums.end(); )        {            if(*itr == *(itr-1))            nums.erase(itr);            else            itr++;        }        return nums.size();    }};

程序基本秒过,但是效率不高,时间为64ms;

vector的删除操作比较耗时。
本题不能直接再申请一块额外的内存用于保存不重复的值;
题干要求只要前length项为单独的不同项即可,至于后面的不管,因此可以用赋值的办法提高效率,舍弃删除的办法。
想法是:用两个迭代器,一个从头到尾扫,另一个记录按照不重复的原则进行赋值。这样,最多只需要赋值N次即可(没有重复的数),不用使用erase函数。速度快一些,37ms。

class Solution {public:    int removeDuplicates(vector<int>& nums) {    if(nums.size() == 0 || nums.size() == 1)    return nums.size();    int length=1;//长度    vector<int>::iterator cur= nums.begin()+1;    for(vector<int>::iterator itr=nums.begin()+1; itr != nums.end(); itr++)    {        if(*itr != *(itr-1))        {            *cur = *itr;            cur++;            length++;        }    }    return length;    }};

80.
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

题目要求与上一题差不多,唯一区别是重复数字可以保有两个。
需要一个标志来区分。
代码如下:20ms。

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() < 3)        return nums.size();        int len=1;        bool flag = false;        vector<int>::iterator itr;        for(itr = nums.begin()+1; itr != nums.end(); )        {            if( *itr == *(itr-1) )            {                if( flag )                {                    nums.erase(itr);                }                else                {                len++;                itr++;                flag = true;                }            }            else            {                len++;                itr++;                flag = false;            }        }        return len;    }};
0 0
原创粉丝点击