Follow up for "Remove Duplicates":
What if duplicates are allowed at mosttwice?
For example,
Given sorted arraynums=[1,1,1,2,2,3]
,
Your function should return length =5
, with the first five elements ofnumsbeing1
,1
,2
,2
and3
. It doesn't matter what you leave beyond the new length.
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 1) return 1;
int i = 1, count = 1;
for (int j = 1; j < nums.length; j++){
if (nums[j] != nums[j - 1]){
count = 1;
nums[i++] = nums[j];
}
else{
if (count < 2){
nums[i++] = nums[j];
count++;
}
}
}
return i;
}
}