
80. Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3]
,
Your function should return length = 5
, with the first five elements of nums being 1
, 1
, 2
, 2
and 3
. It doesn't matter what you leave beyond the new length.
public static int removeDuplicatesMyself(int[] nums) { if (nums.length < 2) return nums.length; final int count = nums.length; int repeat = 2; int occor = 0; int index = 0; for (int i = 0; i < count; ++i) { if (occor < repeat) nums[index++] = nums[i]; if (i < count - 1 && nums[i] == nums[i + 1]) { occor++; } else { occor = 0; } } return index; }
修改repeat可以实现任意重复次数