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].
思路:依然是双指针遍历
代码:
int removeDuplicates(int A[], int n) {
if(n <= 2)
return n;
int res=1;
int i=0;
int j=1;
while(j < n)
{
if(A[i] == A[j])
{
if(j == i+1)
{
A[res++]=A[j];
}
++j;
}
else
{
A[res++]=A[j];
i=j;
++j;
}
}
return res;
}
本文介绍了一个数组去重的算法实现,允许元素重复出现两次。通过双指针技术遍历数组,保留每个元素最多两次出现的机会,同时更新数组并返回新的有效长度。
257

被折叠的 条评论
为什么被折叠?



