LeetCode(80)Remove Duplicates from Sorted Array II

题目

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.

分析

给定一个已排序序列,去除重复元素,使得结果中每个元素的出现次数不超过2;

AC代码

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty())
            return 0;

        int len = nums.size();
        if (len <= 2)
            return len;

        vector<int> ret;
        for (int i = 0; i < len; i++)
        {
            int temp = nums[i];
            int count = 1;
            while (i < (len-1) &&nums[i + 1] == temp)
            {
                i++;
                count++;
            }
            if (count >= 2)
            {
                ret.push_back(nums[i]);
                ret.push_back(nums[i]);
            }
            else if (count == 1)
                ret.push_back(nums[i]);
        }//for

        nums.clear();
        nums = ret;

        return ret.size();
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214846.html