Appearance
Approach: XOR-fold the array; duplicates cancel, leaving the single number.
Complexity: O(n) time, O(1) space
js
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
return nums.reduce(function(ret, num) {
return ret ^ num;
});
};py
from functools import reduce
import operator
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(operator.xor, nums)