Remove Duplicates from Sorted Array II

2018-05-28 15:55:57 浏览数 (1)

问题描述

Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]

myCode

代码语言:javascript复制
/*
 * 对一个已经有序的序列进行重复元素删除
 * 即保证序列相同元素最多出现两次
*/
class Solution1
{
public:
    int removeDuplicatesFromSortedArray(vector<int>& nums)
    {
        //当序列为空时
        if(nums.size() <= 2)
            return nums.size();

        //当序列非空时
        int index = 2;
        for(int i = 2;i<nums.size();i  )
        {
            if(nums[i] != nums[index-2])
            {

                nums[index] = nums[i];
                index  ;
            }
        }
        return index;
    }
};

测试代码

代码语言:javascript复制
#include<iostream>
#include<vector>
using namespace std;
/*
 * 对一个已经有序的序列进行重复元素删除
 * 即保证序列相同元素最多出现两次
*/
class Solution1
{
public:
    int removeDuplicatesFromSortedArray(vector<int>& nums)
    {
        //当序列为空时
        if(nums.size() <= 2)
            return nums.size();

        //当序列非空时
        int index = 2;
        for(int i = 2;i<nums.size();i  )
        {
            if(nums[i] != nums[index-2])
            {

                nums[index] = nums[i];
                index  ;
            }
        }
        return index;
    }
};

//主函数
int main(void)
{

    vector<int> a;
    a.push_back(1);
    a.push_back(1);
    a.push_back(1);
    a.push_back(2);
    a.push_back(2);
    a.push_back(3);
    a.push_back(4);
    a.push_back(4);
    a.push_back(4);
    a.push_back(4);
    a.push_back(5);

    int index = a.size();
    //在删除重复元素之前
    cout<<"before:"<<endl;
    for(int i = 0;i<index;i  )
    {
        cout<<a[i]<<" ";
    }

    cout<<endl;

    //删除重复元素之后
    Solution1 s;
    int return_num = s.removeDuplicatesFromSortedArray(a);
    cout<<"after:"<<endl;
    for(int i = 0;i<return_num;i  )
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
    return 0;
}

0 人点赞