Last active
September 30, 2017 16:44
-
-
Save thatshailesh/edf75b820f6f1661a94551ee767be37e to your computer and use it in GitHub Desktop.
Find three numbers whose sum is 0 in an array
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
var threeSum = function(nums) { | |
let sets = []; | |
let temp = [] | |
nums.sort((a, b) => { | |
return a - b; | |
}); | |
for (let i = 0; i < nums.length; i++) { | |
let target = -nums[i]; | |
let front = i + 1; | |
let back = nums.length - 1; | |
if(target < 0) | |
{ | |
break; | |
} | |
while (front < back) { | |
let sum = nums[front] + nums[back]; | |
// Finding answer which start from number nums[i] | |
if (sum < target) | |
front++; | |
else if (sum > target) | |
back--; | |
else { | |
let triplet = [] | |
triplet[0] = nums[i]; | |
triplet[1] = nums[front]; | |
triplet[2] = nums[back]; | |
sets.push(triplet); | |
// Processing duplicates of Number 2 | |
// Rolling the front pointer to the next different number forwards | |
while (front < back && nums[front] == triplet[1]) front++; | |
// Processing duplicates of Number 3 | |
// Rolling the back pointer to the next different number backwards | |
while (front < back && nums[back] == triplet[2]) back--; | |
} | |
} | |
// Processing duplicates of Number 1 | |
while (i + 1 < nums.length && nums[i + 1] == nums[i]) | |
i++; | |
} | |
return sets; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment