Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zpc7 opened this issue Aug 9, 2022 · 0 comments
Open

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

zpc7 opened this issue Aug 9, 2022 · 0 comments
Labels
简单 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 9, 2022

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;
}
@zpc7 zpc7 added 简单 LeetCode 难度定级 JS and removed JS labels Aug 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
简单 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant