题目
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.
分析
每个元素允许出现两回,把多余的移除
设置两个指针,一个遍历原数组,另一个表示返回的值。
将fast不重复的值赋给slow
class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length <= 2) {
return nums.length;
}
int slow = 2;
for(int fast = 2; fast < nums.length; fast++) {
if(nums[fast] != nums[slow-2]) {
nums[slow++] = nums[fast];
}
}
return slow;
}
}