Skip to content

LeetCode题解:80. 删除有序数组中的重复项 II,JavaScript,详细注释 #360

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

Open
chencl1986 opened this issue Aug 11, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:80. 删除有序数组中的重复项 II

解题思路:

  1. 使用哈希表统计每个数字出现的次数。
  2. 使用指针index指向当前要填入数字的位置。
  3. 次数小等于2时,将当前数字填入index位置,之后将index向后移动一位。
/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
  let map = new Map() // 使用哈希表统计每个数字的数量
  let index = 0 // 用一个指针,指向当前填入合法数字的位置

  // 遍历数组,将出现不超过2次的数字填入相应位置
  for (let i = 0; i < nums.length; i++) {
    // 统计当前出现数字的次数
    map.set(nums[i], map.has(nums[i]) ? map.get(nums[i]) + 1 : 1)

    // 如果当前次数不超过2,将当前数字存入index的位置,之后将index加1,移动到下一个位置
    if (map.get(nums[i]) <= 2) {
      nums[index++] = nums[i]
    }
  }

  // 退出循环时,index的值等于当前新长度
  return index
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant