查找出现奇数次的数字 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/2 4:28:17
给定一个整数数组,我们需要编写一个函数,该函数接受该数组并查找出现奇数次的一个元素。永远只有一个整数出现奇数次。
我们将通过对数组进行排序来解决这个问题。排序后,我们可以遍历数组以选择出现奇数次的元素。
示例
以下是代码 −
const arr = [20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5];
const findOdd = arr => {
let count = 0;
let last;
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++){
if (arr[i] === last) {
count++;
continue;
};
if(count % 2){
return last;
};
last = arr[i];
count = 1;
};
return last;
};
console.log(findOdd(arr));
输出
这将在控制台上产生以下输出 −
5
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

