[LeetCode][JavaScript]Single Number

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?

https://leetcode.com/problems/single-number/

 

 


 

 

要求线性复杂度和不能用额外的空间。

异或运算,两个相同的数,异或的结果是0,一直异或最后剩下的就是结果。

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var singleNumber = function(nums) {
 6     var res = 0;
 7     for(var i = 0; i < nums.length; i++){
 8         res = res ^ nums[i];
 9     }
10     return res;
11 };

 

 

 

posted @ 2015-08-17 23:36  `Liok  阅读(606)  评论(0编辑  收藏  举报