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]
.
1. 引入个变量保存上次重复的值
2. for循环从2开始
public class Solution {
public int removeDuplicates(int[] A) {
if (A.length <= 2) return A.length;
int dup = A[0];
int size = 1;
for (int i = 2; i < A.length; i++) {
if (A[size] != A[i]) {
A[++size] = A[i];
}else {
if (A[i] != dup) {
A[++size] = A[i];
dup = A[i];
}
}
}
return size+1;
}
}