美文网首页
Find the odd int

Find the odd int

作者: Re_Vive | 来源:发表于2018-11-21 09:43 被阅读0次

Question

在一个数字数组中返回只出现单次的
比如:

findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])  // 5
findOdd([1,1,2,-2,5,2,4,4,-1,-2,5])  // -1

Answer

一、forEach遍历
  • 1、查找数组中每个字符出现的次数
  • 2、新建对象,将字符为键,出现次数为值,每次出现值+1
  • 3、循环对象,返回出值为单数的键
function findOdd(a) {
    let l = a.length
    let obj = {}
    a.forEach((val,idx) => {
        !obj[a[idx]] ? obj[a[idx]] = 1 : obj[a[idx]] += 1
    })
    for(let i in obj){
        if(obj[i] % 2 !== 0){
            return parseInt(i)
        }
    }
}
二、reduce
  • 1、使用^运算符,将数组全部进行异或运算
function findOdd(a){
    return a.reduce((a,b) => a^b)
}

第一种是很常规的解法,也是问题比较少的解法
但根据题目能想到第二种的真是惊为天人,使用异或运算,相等的值运算后都为0,双数值都会为0,只剩下一个单数值就是答案

相关文章

网友评论

      本文标题:Find the odd int

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