-
Notifications
You must be signed in to change notification settings - Fork 44
/
Problem40.js
38 lines (34 loc) · 909 Bytes
/
Problem40.js
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
// Problem 40
//
// This problem was asked by Google.
//
// Given an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer.
//
// For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19.
//
// Do this in O(N) time and O(1) space.
//
// https://leetcode.com/problems/single-number-ii/description/
//
// O(N) Time complexity
// O(1) Space complexity
/**
* Returns the non-duplicated integer in a number array where every other number occurs three times
* @param {number[]} nums
* @return {number}
*/
function singleNumber(nums) {
let x1 = 0;
let x2 = 0;
let mask = 0;
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
x2 ^= x1 & num;
x1 ^= num;
mask = ~(x1 & x2);
x2 &= mask;
x1 &= mask;
}
return x1;
}
export default singleNumber;