Last active
August 29, 2015 14:06
-
-
Save okuyan/bcd56493873b6337f57c to your computer and use it in GitHub Desktop.
code challenge
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
| /* | |
| Find all unique triplets in the array which gives the sum of 0. | |
| a + b + c = 0; | |
| [-1, 0, 1, 2, -1, -4] ==> [[-1, 0, 1], [-1, -1, 2]]; | |
| */ | |
| var temp = [-1, 0, 1, 2, -1, -4]; | |
| //a + b + c = 0; >>> a + b = -c; となる組み合わせを探す | |
| var triplets = function(num) { | |
| var len = num.length, | |
| result = []; | |
| num.sort(); | |
| for (var i = 0; i < len; i++) { | |
| //var target = 0 - num[i]; | |
| var target = -1 * num[i]; | |
| var start = i+1, end = len-1; | |
| while (start < end) { | |
| if (num[start] + num[end] == target) { | |
| var solution = []; | |
| solution.push([num[i], num[start], num[end]]); | |
| result.push(solution); | |
| start++; | |
| end--; | |
| while(start<end && num[start] == num[start-1]) | |
| start++; | |
| while(start<end && num[end] == num[end+1]) | |
| end--; | |
| } else if (num[start] + num[end] < target){ | |
| start++; | |
| } else { | |
| end--; | |
| } | |
| } | |
| if (i < len-1) { | |
| while(num[i] == num[i+1]) | |
| i++; | |
| } | |
| } | |
| return result; | |
| }; | |
| console.log(triplets(temp)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment