题目如下:
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. oldIndex, newIndex 两个index协调工作。和前面这道题目思路一样。
我的代码:
//233 ms
public class Solution {
public int removeDuplicates(int[] A) {
if (A.length <3) return A.length;
int newIndex = 2;
for (int oldIndex = 2; oldIndex < A.length; ++oldIndex) {
if (!(A[oldIndex] == A[newIndex - 1] && A[oldIndex] == A[newIndex - 2])) {
A[newIndex++] = A[oldIndex];
}
}
return newIndex;
}
}