Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
相似题目:Remove Duplicates from Sorted Array
快慢指针
时间复杂度:O(n)
空间复杂度:O(1)
public int removeDuplicates(int[] nums) {
int length = nums.length;
if(length <= 1)
return length;
int count = 0;
int temp = nums[0];
int slow = 0;
int fast = 0;
while(fast < length){
if(count <= 1 && nums[fast] == temp){
nums[slow++] = nums[fast++];
count++;
}else if(count >= 2 && nums[fast] == temp){
fast++;
count++;
}else if(nums[fast] != temp){
count = 1;
temp = nums[fast];
nums[slow++] = nums[fast++];
}
}
return slow;
}