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.
题解
和上一题《Remove Duplicates from Sorted Array》类似,只是这里允许一个元素出现2次。所以会比上一题复杂一点。
这里做法与上一题类似,只是比较的不是前一个数,而是前前一个数。
即[1,1,1,2,2,3]中,一开始第三个元素1和第一个元素1比,中间运行有一个相同的数,所以可以达到题目的要求。
/cpp
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<=2)
return nums.size();
int index=2;
for(int i=2;i!=nums.size();i++)
{
if(nums[i]!=nums[index-2])
nums[index++]=nums[i];
}
return index;
}
};