Single Number
Description
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
Solution(javascript)
/** TODO 空间不满足要求
* @param {number[]} nums
* @return {number}
*/
const singleNumber = function (nums = []) {
const map = nums.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1
return acc
}, {})
for (const [key, count] of Object.entries(map)) {
if (count === 1) {
return Number(key)
}
}
return -1
}