1.问题描述
LeetCode:
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]
2.问题分析
在已排序的数组中,移除出现次数大于二的数字(最多保留两个)。
使用快慢索引:
0、如果数组长度不大于2,直接返回数组长度;
1、索引i负责从第3个元素往后依次遍历整个数组;
2、索引index从第3个元素往后,负责记录去重之后数组长度(永远指向去重后数组最后一个元素后一个位置);
3、不断比较索引i和索引(index-2)位置的数是否相等:
不相等则将索引i指向的数复制到索引index指向的位置,然后将index加一。
4、最后返回index。
3.代码
#include <iostream>
using namespace std;
class Solution
{
public:
int removeDuplicates(int A[], int n)
{
if(n <= 2) return n;
int index = 2;
for(int i = 2; i < n; i++)
{
if(A[i] != A[index-2])
A[index++] = A[i];
}
return index;
}
};
//测试
int main(int argc, char* argv[])
{
Solution A;
int b[7] = {1,2,2,2,3,3,3};
int length = A.removeDuplicates(b,7);
cout << length << endl;
system("pause");
return 0;
}
4.总结
本题的关键在于加一个变量记录一下元素出现的次数。