RemoveDuplicates { public int removeDuplicatesAtMostTwice(int[] nums) { int newLen = 0; if (nums.length > 0) { int pos1 = 0; int pos2 = pos1 + 1; while (pos2 < nums.length) { if (nums[pos2] != nums[pos1]) { int clen = pos2 > pos1 + 1 ? 2 : 1; if (pos1 != newLen) { System.arraycopy(nums, pos1, nums, newLen, clen); } newLen += clen; pos1 = pos2; pos2 = pos1 + 1; } else { pos2++; } } int clen = pos1 < nums.length - 1 ? 2 : 1; if (pos1 != newLen) { System.arraycopy(nums, pos1, nums, newLen, clen); } newLen += clen; } return newLen; }  int removeDuplicates(int[] nums); int removeDuplicatesAtMostTwice(int[] nums);  }
@Test(dataProvider = "removeDuplicatesMostTwiceObjects") public void testRemoveMostTwiceDuplicates(int[] array, int[] expected) { int len = new RemoveDuplicates().removeDuplicatesAtMostTwice(array); int[] actual = IntStream.of(array).limit(len).toArray(); assertEquals(actual, expected); }