Back

找出出现奇数次的数

已知给的由整数构成的数组里只有一个数会出现奇数次,返回这个数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function findOdd(A) {
  const map = {};
  for (let num of A) {
    if (!map[num]) map[num] = 1;
    else map[num]++;
  }
  for (let p in map) {
    if (map[p] % 2 === 0) continue;
    else return parseInt(p);
  }
}

涉及到[[遍历对象]] [[余数%]] [[break vs. continue]] [[数字与字符串转换]]

对象的特性是字符串,即使在添加时用的数字也会转换成字符串。

for of 循环改写成 forEach:

1
A.forEach((num) => (map[num] = map[num] ? map[num] + 1 : 1));

or

1
A.forEach((num) => (map[num] ? map[num]++ : (map[num] = 1)));

[[三元运算符]]的操作数可以是赋值语句?

Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy
© Licensed Under CC BY-NC-SA 4.0