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].
public class Solution {
public int removeDuplicates(int[] A) {
if(A.length<=2){
return A.length;
}else{
int count =1;
int num=1;
int val=A[0];
for(int i=1;i<A.length;i++){
if(A[i]==val){
if(count<2){
count++;
A[num++]=val;
}
}else{
val=A[i];
A[num++]=val;
count=1;
}
}
return num;
}
}
}
本文探讨了如何在已排序的数组中移除最多出现两次的重复元素,确保数组长度减小后的结果符合指定条件。通过实例演示算法实现过程,包括初始化变量、遍历数组以及更新结果数组的操作。
788

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



