首页 > 代码库 > LeetCode 136. Single Number

LeetCode 136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

 

分析:

使用^即可,最后剩余的结果就是我们需要的。

/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function(nums) {
    let result = 0;
    for(let i = 0; i <nums.length; i++) {
        result^= nums[i];
    }
    return result;
};

 

LeetCode 136. Single Number