Skip to content

26. 删除有序数组中的重复项 #30

Open
@zpc7

Description

@zpc7

26. 删除有序数组中的重复项

方法1 快慢指针

参考题解: https://leetcode.cn/problems/remove-duplicates-from-sorted-array/solution/kuai-man-zhi-zhen-26-shan-chu-you-xu-shu-8v6r/

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    if(nums.length == 0){return 0;}
    let slow = 0, fast = 1;
    while(fast < nums.length){
        if(nums[fast] != nums[slow]){
            slow = slow + 1;
            nums[slow] = nums[fast];
        }
        fast = fast + 1;
    }
    return slow + 1;
};

方法2 通过统计重复的个数, 反向计算需要修改的位置

function removeDuplicates(nums) {
  let count = 0;//重复的数字个数
  
  for (let right = 1; right < nums.length; right++) {
    if (nums[right] === nums[right - 1]) {
      //如果有重复的,count要加1
      count++;
    } else {
      //如果没有重复,后面的就往前挪, 覆盖
      nums[right - count] = nums[right];
    }
  }
  //数组的长度减去重复的个数
  return nums.length - count;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    简单LeetCode 难度定级

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions