-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleNumber.js
More file actions
43 lines (36 loc) · 825 Bytes
/
singleNumber.js
File metadata and controls
43 lines (36 loc) · 825 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* LeetCode 136. Single Number
* https://leetcode.com/problems/single-number/description/
*
* Given a non-empty array of integers nums, every element appears twice except
* for one. Find that single one.
*
* You must implement a solution with linear runtime complexity and use only
* constant extra space.
*/
/**
* @param {number[]} nums
* @return {number}
*/
const singleNumber = (nums) => {
let result = 0;
for (const num of nums) {
result ^= num; // Bitwise XOR assignment
}
return result;
};
/*
function singleNumberSlow(nums) {
const set = new Set();
for (let i = 0; i < nums.length; i++) {
if (set.has(nums[i])) {
set.delete(nums[i]);
} else {
set.add(nums[i]);
}
}
const [firstValue] = set;
return firstValue;
}
*/
module.exports = { singleNumber };