首页 > 代码库 > Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Follow up the "remove duplicates",what if duplicates are allowed at most twice?

思路一:使用变量numlength记录数组中相同数字出现不超过两次所得到的数组长度;

code:

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n==0)            return 0;        else if(n==1)            return 1;                int numlength=1;        int numtmp=A[1];                for(int i=2;i<n;++i)        {            if(A[i]!=A[i-2])            {                A[numlength++]=numtmp;                numtmp=A[i];            }        }                A[numlength++]=numtmp;                return numlength;    }};
View Code

还有一种写法,思路与上面类似,但是更加直观,引入变量occur记录出现的次数;

code:

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n==0)            return 0;                int numlength=0;        int occur=1;        for(int i=1;i<n;++i)        {            //若前行过程中遇到相同的数字,则判定该数字已经出现的次数,不允许超过两次            if(A[numlength]==A[i])            {                if(occur<2)                {                    A[++numlength]=A[i];                    ++occur;                }            }            //若不相同,occur赋值为1            else            {                A[++numlength]=A[i];                occur=1;            }        }                return numlength+1;    }};
View Code

 在此问题中,数组已经排好序,但是若未排序,则可使用一hashmap记录数字出现的次数,然后进行判断,若出现次数<2,则执行插入操作;思路基本同上,本例使用STL中的map实现。当然也可以对数组进行排序后进行,两者各有优势;

code:

#include<iostream>#include<map>using namespace std;int main(){    map<int,int>hashmap;    map<int,int>::iterator ite=hashmap.begin();    int arr[6]={1,2,1,2,1,3};    int numlength=0;    for(int i=0;i<6;++i)    {        ite=hashmap.find(int(arr[i]));        if(ite==hashmap.end())        {            pair<int,int>value(int(arr[i]),1);            hashmap.insert(value);            arr[++numlength]=arr[i];        }        else        {            if(ite->second<2)            {                //通过迭代器可以修改value,not key                ++ite->second;                arr[++numlength]=arr[i];            }        }    }    cout<<numlength+1<<endl;    return 0;}
View Code

 

Remove Duplicates from Sorted Array