Created
August 29, 2018 19:01
-
-
Save venil7/0cfdb434f0a22a613928dc446bdbb3c3 to your computer and use it in GitHub Desktop.
pairs of array that sum to X, O(n)
This file contains hidden or 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
| let pairs = (arr: number[], s: number): number[][] => { | |
| let cache = {}; | |
| let res = []; | |
| for (let i of arr) { | |
| if (!cache[i]) { | |
| cache[i] = true; | |
| } | |
| let snd = s - i; | |
| if (cache[snd]) { | |
| res.push([i, snd]); | |
| } | |
| } | |
| return res; | |
| }; | |
| let res = pairs([1, 2, 4, 3, 0, 5, 9, 6, 8, 7].sort(), 7); | |
| console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment