-
Notifications
You must be signed in to change notification settings - Fork 269
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #207 from Ahtaxam/master
Add 3-sum problem with improvement issue #208
- Loading branch information
Showing
3 changed files
with
59 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
const threeSum = function(nums) { | ||
// sort the array | ||
nums = nums.sort((a, b) => a - b); | ||
|
||
let result = []; | ||
// iterate through the array and use two pointers to find the sum | ||
for (let i = 0; i < nums.length; ++i) { | ||
let left = i + 1; | ||
let right = nums.length - 1; | ||
while (left < right) { | ||
let sum = nums[i] + nums[left] + nums[right]; | ||
if (sum == 0) { | ||
result.push([nums[i], nums[left], nums[right]]); | ||
left++; | ||
right--; | ||
} | ||
else if (sum < 0) { | ||
left++; | ||
} | ||
else { | ||
right--; | ||
} | ||
} | ||
// skip duplicates | ||
while (i < nums.length - 1 && nums[i] == nums[i + 1]) { | ||
i++; | ||
} | ||
} | ||
|
||
// initialize set to remove duplicate | ||
const set = new Set(result.map(JSON.stringify)); | ||
// final output array | ||
output = (new Array(...set).map(JSON.parse)); | ||
return output; | ||
}; | ||
|
||
|
||
module.exports = threeSum; | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
const threeSum = require("./3sum"); | ||
|
||
describe("threeSum", () => { | ||
it("Should return [[-1, -1, 2], [-1, 0, 1]]", () => { | ||
expect(threeSum([-1, 0, 1, 2, -1, -4])).toEqual([ | ||
[-1, -1, 2], | ||
[-1, 0, 1], | ||
]); | ||
}); | ||
|
||
it("Should return [[0, 0, 0]]", () => { | ||
expect(threeSum([0, 0, 0])).toEqual([[0, 0, 0]]); | ||
}); | ||
|
||
it("Should return [[-1, -1, 2]]", () => { | ||
expect(threeSum([-1, 2, -1, -4])).toEqual([[-1, -1, 2]]); | ||
}); | ||
|
||
}); |