Last active
October 11, 2018 22:54
-
-
Save lienista/5d323213a5b5a3e58940490e29ee049e to your computer and use it in GitHub Desktop.
(Algorithms in Javascript) Leetcode 15. 3Sum - Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets.
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
| const threeSum = (nums) => { | |
| let len = nums.length; | |
| if(len < 3) return []; | |
| nums.sort(function(a,b){ | |
| return a-b; | |
| }) | |
| if(nums[0] > 0 || nums[0] + nums[1] + nums[2] > 0) return []; | |
| if(len === 3) { | |
| if(nums[0] + nums[1] + nums[2] === 0) return [nums]; | |
| else return []; | |
| } | |
| //console.log(nums); | |
| let result = []; | |
| let checker = ''; | |
| for(let i=0; i<len; i++){ | |
| var sum = -nums[i]; | |
| for(let j=i+1, k = len - 1; j<k;){ | |
| //console.log(i + ', ' + j + ', ' + k + ': ' + nums[i] + ', ' + nums[j] + ', ' + nums[k]); | |
| var temp = nums[j] + nums[k]; | |
| if(temp < sum){ | |
| j++; | |
| } else if(temp > sum){ | |
| k--; | |
| } else { | |
| var triplet = [nums[i], nums[j], nums[k]]; | |
| result.push(triplet); | |
| //skip j term if it's a duplicate | |
| while(nums[j] === nums[j+1] && j<len) j++; | |
| //skip k term if it's a duplicate | |
| while(nums[k] === nums[k-1] && k>0) k--; | |
| j++; | |
| k--; | |
| } | |
| } | |
| //skip i term if it's a duplicate | |
| while(nums[i] === nums[i+1] && i<len) i++; | |
| } | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment