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.
代码:
int removeDuplicates(vector<int>& nums)
{
int sum = 1, tmp = 1, fg = 1;
if(nums.size() == 0) return 0;
sort(nums.begin(), nums.end());
for(int i = 1; i < nums.size(); i ++)
{
if(nums[i] == nums[i-1])
{
if(tmp < 2)
{
nums[fg ++] = nums[i];
tmp = tmp + 1;
sum = sum + 1;
}
}
else
{
nums[fg ++] = nums[i];
tmp = 1;
sum = sum + 1;
}
}
return sum;
}