# 【Leet Code】80. Remove Duplicates from Sorted Array II---Medium

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.

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

}
return j+1;
}
};

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() < 1) return 0;
int j = 0, i = 1;

while(i < nums.size())
{
if(nums[i] == nums[j])
{
int k = i + 1;
while(k < nums.size() && nums[k] == nums[i])
++k;
nums[++j] = nums[i];
i = k;
}
else
nums[++j] = nums[i++];

}
return j+1;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：【Leet Code】80. Remove Duplicates from Sorted Array II---Medium 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)