Source: leetcode 136. Single Number
Q. 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?
Answer 1: with using extra memory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| * @param {number[]} nums * @return {number} */ export default function singleNumber (nums) { const seen = new Set() for (let i = 0; i < nums.length; i++) { if (seen.has(nums[i])) { seen.delete(nums[i]) } else { seen.add(nums[i]) } } return seen.values().next().value }
|
Answer 2: without using extra memory
1 2 3 4 5 6 7
| * @param {number[]} nums * @return {number} */ export default function singleNumber (nums) { return nums.reduce((curr, prev) => curr ^ prev) }
|