题目:

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

 

相关文章:

  • 2022-12-23
  • 2021-05-29
  • 2021-10-02
  • 2022-01-09
  • 2021-11-17
  • 2021-06-01
猜你喜欢
  • 2022-02-24
相关资源
相似解决方案