Skip to content

LeetCode题解:136. 只出现一次的数字,哈希表,JavaScript,详细注释 #417

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 Apr 6, 2023 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:
https://leetcode.cn/problems/single-number/

解题思路:

  1. 遍历nums,使用Set保存第一次遇到的数字。
  2. 如果第二次遇到相同数字,将其从Set中删除。
  3. 最终Set中只会留下一个数字,即为只出现了一次的数字。
/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function (nums) {
  let set = new Set() // 使用哈希表保存遍历时遇到的数字

  for (const num of nums) {
    // 如果遇到出现过的数字,将其从Set中删除
    if (set.has(num)) {
      set.delete(num)
    } else {
      // 第一次遇到的数字,将其加入Set
      set.add(num)
    }
  }

  // 最终Set中只剩下一个只出现过一次的元素
  return [...set][0]
}
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