Skip to content

Instantly share code, notes, and snippets.

@mrboli
Created April 2, 2020 04:06
Show Gist options
  • Save mrboli/34447d13bfb1d1eb51dc8f673644e58e to your computer and use it in GitHub Desktop.
Save mrboli/34447d13bfb1d1eb51dc8f673644e58e to your computer and use it in GitHub Desktop.
Single Number
// hashmap()
// 56 ms, faster than 87.12%
// 37.2 MB, less than 50.00%
function hashmap (nums) {
let existance = {};
for (let i = 0; i < nums.length; i++) {
if (nums[i] in existance === false)
existance[nums[i]] = 1;
else
delete existance[nums[i]];
}
return Object.keys(existance)[0];
};
// reduce ()
// 56mb ~80%
// 35.3mb 92.31%
// Slower probably because of the inner workings of reduce
// Potentially because it is a property on the Array prorotype, and not a native function
// Might use slightly less memory since the accumulator is bulit in
function reduce (nums) {
return nums.reduce((mask, num) => mask ^ num, 0);
};
// forLoop ()
// 44ms 99.75%
// 36mb 67.31%
// Memory usage higher probably because of the reassignment:
// mask = mask ^ nums[i]; mask has to be held twice
function forLoop (nums) {
let mask = 0;
for (let i = 0; i < nums.length; i++) {
mask = mask ^ nums[i];
}
return mask;
}
// forEach ()
// 56ms 87.12%
// 35.4mb 82.69%
// Slower than for loop
function forEach (nums) {
let m = 0;
nums.forEach(n => m = m ^ n);
return m;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment