【数组】Remove Duplicates from Sorted Array II

时间:2023-12-25 22:31:02

题目:

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 1122 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++;
}
}
};