题目:
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.
思路:
从数组的第三个元素开始遍历,若遇到与A[i-2]相同,则删除A[i]
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
var pre=0,next=2;
if(nums.length<=2){
return nums.length;
} for(var i=2;i<nums.length;){
if(nums[pre]==nums[i]){
nums.splice(i,1);
}else{
pre++;
i++;
}
}
};