Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

15. 3Sum #150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
Loading
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions 53 solutions/3sum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// 15. 3Sum
// https://leetcode.com/problems/3sum/
export default function threeSum(nums: number[]): number[][] {
const triplets: [number, number, number][] = [];

nums.sort((a, b) => a - b);

for (let i = 0; i < nums.length - 2; ++i) {
if (nums[i] > 0) break;
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codacy has a fix for the issue: Expected { after 'if' condition.

Suggested change
if (nums[i] > 0) break;
if (nums[i] > 0) {break;}

if (nums[i] === nums[i - 1]) continue;
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codacy has a fix for the issue: Expected { after 'if' condition.

Suggested change
if (nums[i] === nums[i - 1]) continue;
if (nums[i] === nums[i - 1]) {continue;}


let left = i + 1;
let right = nums.length - 1;
let target = -nums[i];

while (left < right) {
if (nums[left] + nums[right] < target) {
while (nums[left + 1] === nums[left]) {
left += 1;
}

left += 1;

continue;
}

if (nums[left] + nums[right] > target) {
while (nums[right - 1] === nums[right]) {
right -= 1;
}

right -= 1;

continue;
}

triplets.push([nums[i], nums[left], nums[right]]);

while (nums[left + 1] === nums[left]) {
left += 1;
}

while (nums[right - 1] === nums[right]) {
right -= 1;
}

left += 1;
right -= 1;
}
}

return triplets;
}
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.