Last active
October 11, 2018 22:54
-
-
Save lienista/92c0a37c00174a26a2451d3bd8a43aa3 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-2; i++){ | |
for(let j=i+1; j<len-1; j++){ | |
//since the array is sorted, we only need to start from | |
//the last index that where value was found, since | |
//nums[k] has to be a lower number. | |
for(let start = len-1, k = start; k>i, k>j;) { | |
let triplet = [nums[i], nums[j], nums[k]]; | |
let tripletString = '/' + nums[i] + ' ' + nums[j] + ' ' + nums[k] + '/'; | |
if(nums[i] + nums[j] === -nums[k] && !checker.includes(tripletString)){ | |
result.push(triplet); | |
checker += tripletString; | |
start--; | |
k = start; | |
} else { | |
k--; | |
} | |
} | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment