小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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测试程序源码

posted on 2015-09-18 21:15  Coding菌  阅读(117)  评论(0编辑  收藏  举报