80. Remove Duplicates from Sorted Array II

来源:互联网 发布:神经网络数据预处理 编辑:程序博客网 时间:2024/04/28 15:52

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 ofnums being 1, 1, 2, 2 and3. It doesn't matter what you leave beyond the new length.


遍历数组,用count值来存储当前数字已经出现了几次,超过两次就从vector中erase掉。需要注意的是因为erase后后面的元素依次前移,因此需要把i--。

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


0 0
原创粉丝点击