美文网首页
LeetCode题解:137. 只出现一次的数字 II,哈希表,

LeetCode题解:137. 只出现一次的数字 II,哈希表,

作者: Lee_Chen | 来源:发表于2023-03-14 13:12 被阅读0次

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

解题思路:

  1. 使用哈希表统计所有数字出现的次数。
  2. 遍历哈希表,遇到出现次数为1的数字,就将其返回
/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function (nums) {
  let map = new Map() // 使用哈希表统计数字出现的次数

  // 遍历nums,统计每个数字出现的次数
  for (const num of nums) {
    map.set(num, map.has(num) ? map.get(num) + 1 : 1)
  }

  // 遍历哈希表,遇到出现次数为1的数字,即返回
  for (const [num, count] of map) {
    if (count === 1) {
      return num
    }
  }
}

相关文章

网友评论

      本文标题:LeetCode题解:137. 只出现一次的数字 II,哈希表,

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