js implements removing duplicates in sorted arrays

JavaScriptjs implementation to remove duplicates in a sorted array.

Original question: Given an array nums in ascending order, please delete the repeated elements in place so that each element appears only once, and return the new length of the deleted array. The relative order of elements should be consistent. Since the length of the array cannot be changed in some languages, the result must be placed in the first part of the array nums. More canonically, if there are k elements after removing duplicates, then the first k elements of nums should hold the final result. Returns k after inserting the final result into the first k positions of nums. Instead of using extra space, you have to modify the input array in-place and do so using O(1) extra space.
Author: LeetCode
Link: https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2gy9m/
Source: LeetCode

This question adopts the method of double pointers , define a first pointer left , and start traversing the array from left plus 1 item. When traversing, i is equivalent to the right pointer . If nums[left]!=nums[i], you can give left Add 1, and assign the array item at position i to the position plus 1 at left. If nums[left]==nums[i], then skip this cycle, and i continues to move to the right.
That is to say, when there is a left pointer, it will start from the first element in the back and compare it with the front one by one , until it finds an element different from the element pointed by the left pointer, moves the left to the right, and assigns the value of the found element to the left at this time the location indicated.
After we rearrange the array, we need to cut off the left+1 position and the array elements behind it, and then return the length of the array.

具体代码如下:
/**
 * @param {number[]} nums
 * @return {number}
 */
 // 双指针法
var removeDuplicates = function(nums) {
    
    
    if(nums.length==0){
    
    
        return;
    }
    // 定义一个左指针
    var left = 0;
    // 循环遍历数组
    for(var i = left+1;i<nums.length;i++){
    
    
        if(nums[left]!==nums[i]){
    
    
            left=left+1;
            nums[left]=nums[i];
        }
       continue;
    }
    nums.splice(left+1,nums.length-1);
    return nums.length;
};

Guess you like

Origin blog.csdn.net/weixin_52797317/article/details/128731428