题目:
给定一个已排序的数组,将重复项移除到位,这样每个元素只出现一次,并返回新的长度。
不要为另一个数组分配额外的空间,必须在内存恒定的情况下就地分配。
例如,
给定输入数组a=[1,1,2],
您的函数应该返回length=2,而a现在是[1,2]。
public class Solution {
public int removeDuplicates(int[] A) {
int len = A.length;
int cnt = 1;
for(int i=1;i<len;i++){
if(A[i]==A[i-1])continue;
A[cnt++] = A[i];
}
return cnt;
}
}
“删除重复项”的后续操作:
如果最多允许重复两次呢?
例如,
给定排序数组a=[1,1,1,2,2,3],
函数返回的长度应为5,现在a为[1,1,2,2,3]。
public class Solution {
public int removeDuplicates(int[] A) {
int len = A.length;
if(len==0) return 0;
int res = 1;
int count = 1;
int tmp = A[0];
for(int i=1;i<len;i++){
if(A[i]!=tmp){//与前一个不相等
count=1;
tmp=A[i];
A[res++] = A[i];
}
else if(A[i]==tmp&&count<2){//与前一个相等但只出现过第二次
A[res++] = A[i];
count=2;
}
else{
count++;
}
}
return res;
}
}