Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
善用返回值!
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int lastInt = A[0]-1;
int lastIntTime = 0;
int length = 0;
for(int i=0;i<n;i++)
{
if(A[i]==lastInt)
{
lastIntTime ++;
}
else
{
lastIntTime = 1;
}
lastInt = A[i];
if(lastIntTime<3)
{
length++;
A[length-1] = A[i];
}
}
return length;
}
};
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].
本文探讨了如何在已排序的数组中移除最多出现两次的重复元素,通过实现一个高效的算法,确保数组长度减小,同时保留不超过两次的重复元素。
711

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



