
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
原文地址:http://blog.csdn.net/keyyuanxin/article/details/45950481