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 class Solution {
public int removeDuplicates(int[] nums) {
int len = 0, count = 0;
if (nums.length < 3) {
return nums.length;
}
for (int i = 0; i < nums.length; i ++) {
if (i != 0 && nums[i] == nums[i - 1]) {
while (i < nums.length && nums[i] == nums[i - 1])
i ++;
nums[len ++] = nums[i - 1];
}
if (i < nums.length)
nums[len ++] = nums[i];
}
return len;
}
}
而后看到一种优秀的解法:
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}
这样做可以推广到任意的允许x遍重复,只需把判断条件if (i < 2 || n > nums[i-2])修改成if (i < x || n > nums[i-x])。