LeetCode每日一题:remove duplicates f
2017-05-18 本文已影响13人
yoshino
问题描述
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 int removeDuplicates(int[] A) {
if (A.length == 0 || A.length == 1) return A.length;
int count = 1;
int twice = 0;
for (int i = 1; i < A.length; i++) {
if (A[i] != A[i - 1]) {
A[count] = A[i];
count++;
twice = 0;
} else {
twice++;
if (twice < 2) {
A[count] = A[i];
count++;
}
}
}
return count;
}