Last active
May 8, 2023 14:50
-
-
Save zyxd/2a88e9526cc4ee19b64295628bac6573 to your computer and use it in GitHub Desktop.
One of 3Sum (https://leetcode.com/problems/3sum) solution
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 unique = (array) => Array.from( | |
new Set(array.map(x => JSON.stringify(x))), | |
x => JSON.parse(x) | |
) | |
const combinations = (array) => new Array(1 << array.length) | |
.fill() | |
.map((_, i) => array.filter((_, j) => i & (1 << j))) | |
const threeSum = (array) => combinations(array) | |
.filter((t) => t.length === 3) | |
.filter(([a, b, c]) => a + b + c === 0) | |
.map((t) => t.sort()) | |
.map((t) => JSON.stringify(t)) | |
.reduce((a, t) => ([...a, ...(!a.includes(t) ? [t] : [])]), []) | |
.map((t) => JSON.parse(t)) | |
threeSum([-1, 0, 1, 2, -1, -4]) | |
// [[-1, 0, 1], [-1, -1, 2]] | |
threeSum([0, 1, 1]) | |
// [] | |
threeSum([0, 0, 0]) | |
// [[0, 0, 0]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment