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.
思路
筛选重复的,最多留下两个。后一个与前面一个比,相同就让后一个加入,不相同也是让后一个加入。这样就实现每个值最多出现两次。
class Solution {
public:
int removeDuplicates(vector<int>& A) {
int n = A.size();
int j = 0, t = 1;
int count = 1;
if(n == 0)
return 0;
if(n == 1)
return 1;
A[0] = A[0];
for(int i = 1; i < n; i++, j++)
{
if(A[i] == A[j] && count < 2)
{
A[t++] = A[i];
count++;
}
else if(A[i] != A[j])
{
A[t++] = A[i];
count = 1;
}
}
/*for(i = 0; i < t; i++)
cout<<A[i]<<" ";*/
return t;
}
};