/** * 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]. * * “删除重复项”的后续
/**
* 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].
*
* “删除重复项”的后续操作:
* 如果最多允许重复两次呢?
* 例如,
* 给定排序数组a=[1,1,1,2,2,3],
* 函数返回的长度应为5,现在a为[1,1,2,2,3]。
*/
因为本题是 允许重复两次的数,所以我们将count = 2,来进行循环。
/** * 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]. * * “删除重复项”的后续操作: * 如果最多允许重复两次呢? * 例如, * 给定排序数组a=[1,1,1,2,2,3], * 函数返回的长度应为5,现在a为[1,1,2,2,3]。 */ public class Main48 { public static void main(String[] args) { int[] A = {1,1,1,2}; System.out.println(Main48.removeDuplicates(A)); } public static int removeDuplicates(int[] A) { if (A == null) { return 0; } if (A.length<=2) { return A.length; } int count = 2; for (int i=2;i<A.length;i++) {//如果一样的话 就跳过。
if (A[i] != A[count-2]) { //一旦跟它前面的第二个数不一样 就相当于加入数组中,覆盖前面循环一样的数的位置。 A[count++] = A[i]; } } return count; } }