力扣刷题-26.删除有序数组中的重复项

84 阅读1分钟

第一次写,用的数组原型上的方法,但写算法题好像一般不使用这些方法

var removeDuplicates = function(nums) {
    nums.forEach( (item,index) => {
        let leftIndex = index-1
        while(nums[index]===nums[leftIndex]){
            nums.splice(leftIndex,1)
        }
    })
    return nums.length
};

看力扣学习其它题解:

思路:双指针

要求删除重复元素,实际上就是将不重复的元素移到数组的一侧。

var removeDuplicates = function(nums) {
    let l = 0
    let r = 1
    for(let i = 0,len = nums.length;i < len;i++){
        if(nums[l] === nums[r]) 
            r++
        else {
            l++
            nums[l] = nums[r]
            r++
        }
    }
    nums = nums.slice(0,l)
    return nums.length
};
console.log(removeDuplicates([0,0,1,1,1,2,2,3,3,4]))