标签:leetcode
链接: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