码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode No80. Remove Duplicates from Sorted Array II

时间:2016-08-06 20:37:57      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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次,删除重复超过3次的元素,返回删除后的长度。

Algorithm:

见程序

Accepted Code:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()<=2)return nums.size();
        vector<int>::iterator it=nums.begin();
        for(;it!=nums.end();)
        {
            int temp=*it;
            int j=0;
            while(*it==temp)
            {
                if(it==nums.end())
                    break;
                j++;
                if(j>2)
                    nums.erase(it);
                else
                    it++;
            }
        }
        return nums.size();
    }
};


leetcode No80. Remove Duplicates from Sorted Array II

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52137976

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!