美文网首页
26. Remove Duplicates from Sorte

26. Remove Duplicates from Sorte

作者: Icytail | 来源:发表于2017-11-04 15:54 被阅读0次

    Description:

    Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
    Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

    Example:

    Given nums = [1,1,2],
    
    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
    It doesn't matter what you leave beyond the new length.
    

    My code:

    /**
     * @param {number[]} nums
     * @return {number}
     */
    // 从数组下标0开始,判断当前位与下一位是否相同,如果相同,则把当前位之后的元素都往前移一位 (一个外部循环+一个if+一个前移循环)
    // 还要再判断往前移了以后的当前位是否还是和下一位相同 (一个if)
    var removeDuplicates = function(nums) {
        let i = 0;
        while(i < nums.length - 1) {
            if(nums[i] == nums[i + 1]) {
                for(let j = i; j < nums.length; j++) {
                    nums[j] = nums[j + 1];
                }
                nums.pop();
            }
            if(nums[i] == nums[i + 1]) {
                continue;
            } else {
                i++;
            }
        }
        return nums.length;
    };
    

    Note: 由于题目要求使用in-place,不然可以直接把转换为set类型转换再变成数组,简单粗暴

    相关文章

      网友评论

          本文标题:26. Remove Duplicates from Sorte

          本文链接:https://www.haomeiwen.com/subject/lwofmxtx.html