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

80 Remove Duplicates from Sorted Array II

时间:2015-07-14 15:37:17      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:leetcode

80 Remove Duplicates from Sorted Array II

链接:https://leetcode.com/problems/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.

Hide Tags Array Two Pointers

允许两个重复元素出现,否则删除多余的元素。题目和Remove Duplicates from Sorted Array相似,但是这一题需要多一个变量来控制可以有两个重复元素。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()<3)return nums.size();
        int result=0;
        bool flag=true;
        for(int i=1;i<nums.size();i++)
        {
          if(nums[i]!=nums[result])
          {
              nums[++result]=nums[i];
              flag=true;
          }
          else if(flag)
          {
              nums[++result]=nums[i];
              flag=false;
          }

        }
        return result+1;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

80 Remove Duplicates from Sorted Array II

标签:leetcode

原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46877947

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