题目描述:
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
分析:双指针思想。和26题的Remove Duplicates from Sorted Array思路类似。只是此题允许最多能有2个重复的元素,因此在用双指针处理的时候,指针修改的条件要变化一下。
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
分析:双指针思想。和26题的Remove Duplicates from Sorted Array思路类似。只是此题允许最多能有2个重复的元素,因此在用双指针处理的时候,指针修改的条件要变化一下。
思路:若数组的size小于3,直接返回其size。若size大于3,那么指定前后迭代器间隔为2,循环中,首先比较两者所指元素是否相等,若相等,则直接删除后迭代器所指元素,将直接返回指向被删除元素的下一个元素的迭代器,继续循环处理。直到有迭代器指向nums.end().
以下是C++实现代码:
/*//20ms///*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int size = nums.size();
if(nums.empty())
return 0;
if(size < 3) //不足3个元素,直接返回数组大小
return size;
vector<int>::iterator itr1 = nums.begin();
vector<int>::iterator itr2 = itr1 + 2; //间隔为2,因为允许存在两个重复的元素
while(itr2 != nums.end())
{
if(*itr1 == *itr2) //两者所指元素相等,那么直接删除右迭代器所指元素,函数返回下一个元素的迭代器
{
itr2 = nums.erase(itr2);
}
else //若不相等,两个迭代器右移一个位置
{
itr1++;
itr2 ++;
}
}
return nums.size(); //返回修改后的数组大小
}
};