Remove Duplicates from Sorted Array II
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.
图解
分析
- about special case, when nums.length small and equal to 2 , return nums.length, that is the minimum length this function could return
- two pointers : slow and fast, initially to be 1
- scan the array from index 2 to rightmost, using fast pointer, when nums[fast] is not equal to nums[fast-2], we assign nums[fast] to nums[slow] and increment slow
代码
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length<=2) return nums.length;
int base = 2;
for(int i = 2;i<nums.length;i++){
if(nums[i]!=nums[base-2]){
nums[base]=nums[i];
base++;
}
}
return base;
}
}