Remove Duplicates from Sorted Array II

来源:互联网 发布:淘宝店铺旺旺在哪里 编辑:程序博客网 时间:2024/06/05 19:53

一、问题描述

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 1122 and 3. It doesn't matter what you leave beyond the new length.

二、思路

去除数组中重复数大于2的元素,并将数组最后长度返回。

最关键的地方在于判断多余的变量flag,由于是有序数组,当下一个元素和当前元素不同时,flag变量重新赋值为0。还有vector的erase函数必须要注意参数类型是string::iterator的类型,而且删除元素后指向下一个元素,所以我们用--i将指针回到原位置。

三、代码

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int n = nums.size();        int flag = 0;        for(int i = 1; i < n; ++i){            if(nums[i] == nums[i - 1]){                flag++;                if(flag > 1){                    --n;                    nums.erase(nums.begin() + i);                    --i;                }            }else{                flag = 0;            }        }        return n;    }};


0 0
原创粉丝点击