问题描述:Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]
分析:两个重复的ok,三个重复的不会计入有效长度,即一个数字最多只能出现两次,所以定义两个指针,i和index,两个指针之间相差为2,判断是否相等,不相等才会计入index,相等就证明了有三个一样的,直接pass,不计入index
代码:
class Solution
{
int Fun(vector<int> &arr)
{
if(arr.size() <= 2)
{
return arr.size();
}
int index = 2;
for(int i = 2;i < arr.size();i++)
{
if(arr[index] != arr[i-2])
{
arr[index++] = arr[i];
}
}
return index;
}
};