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

leetcode_80_Remove Duplicates from Sorted Array II

时间:2015-05-24 11:37:57      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   array   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


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.


//方法一:通过count计数是否重复了2次
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() == 0)
            return 0;
        int length = 0;
        int count = 1;
        for(int i=1; i<nums.size(); i++)
        {
            if(nums[length] != nums[i])
            {
                nums[++length] = nums[i];
                count = 1;
            }
            else
            {
                count++;
                if(count < 3)
                    nums[++length] = nums[i];
            }
        }
        return length+1;
    }
};

//方法二:参考,和length-2个数做比较
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() < 2)
            return nums.size();
        int length = 2;
        for(int i=2; i<nums.size(); i++)
        {
            if(nums[length-2] != nums[i])
                nums[length++] = nums[i];
        }
        return length;
    }
};




leetcode_80_Remove Duplicates from Sorted Array II

标签:c++   leetcode   array   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/45950481

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