Given a non-empty 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?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
先提供一种最容易想到的方法,在js方法中只胜过64%的算法
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
var catchIndex = false;
var a= {};
for (i=0; i<nums.length; i++){
if (typeof a[nums[i]] == 'undefined') {
a[nums[i]] = 1;
} else {
a[nums[i]] += 1;
}
}
for (item in a) {
if (a[item] == 1) {
catchIndex = item;
}
}
return catchIndex;
};
xor的解决方法,胜过95%的js算法;
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
var catchIndex = false;
result = nums[0];
for (i=1; i<nums.length; i++){
result ^= nums[i];
}
return result;
};