找出出现奇数次数的数

Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.


function findOdd(A) {
  //happy coding!
 var hash = new Array();
 var map  = new Array();
  for(var i=0;iif(A[i]<0)
    {
        if(isNaN(hash[map[-A[i]]]))
            map[-A[i]] = 0;
        map[-A[i]]++;
    }
    else
    {
        if(isNaN(hash[A[i]]))
            hash[A[i]] = 0;
        hash[A[i]] ++;
    }

  }
  for(var i=0;iif(hash[i]%2)
    {
        return i;
    }
  }
  for(var i=0;iif(map[i]%2)
    {
        return -i;
    }

  }
}

function doTest(a, n) {
  console.log("A = ", a);
  console.log("n = ", n);
  Test.assertEquals(findOdd(a), n);
}
Test.describe('Example tests', function() {
  doTest([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5], 5);
  doTest([1,1,2,-2,5,2,4,4,-1,-2,5], -1);
  doTest([20,1,1,2,2,3,3,5,5,4,20,4,5], 5);
  doTest([10], 10);
  doTest([1,1,1,1,1,1,10,1,1,1,1], 10);
  doTest([5,4,3,2,1,5,4,3,2,10,10], 1);
});



刚开始学js,还只是知道怎么解,不太会灵活运用。看到一个妙解如下

const findOdd = (xs) => xs.reduce((a, b) => a ^ b);

就这一句……….没有对比就没有伤害,秒成渣 ^_^,继续加油。
ps.说明下,这一句代码综合了reduce的递归调用,arrow function,还有异或运算符的特性。

你可能感兴趣的:(codewars)