Created
November 4, 2017 11:39
-
-
Save levymoreira/e3d5b5ed02a0b35c41ddea8e3680cb55 to your computer and use it in GitHub Desktop.
Given an array of integers, return the number of pairs whose sum is K
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const _ = require('underscore'); | |
class FindSum { | |
// O(n) | |
find(arr, totalSum) { | |
const m = new Map(); | |
// O(n) | |
arr.forEach((value) => { | |
if (m.get(value) !== undefined) { | |
m.set(value, m.get(value) + 1); | |
} else { | |
m.set(value, 1); | |
} | |
}) | |
let result = 0; | |
// O(n) | |
arr.forEach((value) => { | |
if (m.get(totalSum - value) !== undefined) { | |
result += m.get(totalSum - value); | |
} | |
if ((totalSum - value) === value) { | |
result--; | |
} | |
}) | |
return result / 2; | |
} | |
} | |
const test = (currentResult, expectedResult) => { | |
if (!_.isEqual(currentResult, expectedResult)) { | |
console.log('Error!'); | |
console.log('Current Result:'); | |
console.log(currentResult); | |
console.log('Expected Result:'); | |
console.log(expectedResult); | |
} else { | |
console.log('Success.'); | |
} | |
} | |
var obj = new FindSum(); | |
test(obj.find([9,1,3,11,8,7,5,5], 10), 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment