LeetCode: 3sum Solution

1/**
2 * @param {number[]} nums
3 * @return {number[][]}
4 */
5var threeSum = function (nums) {
6 const N = nums.length
7 const res = new Set()
8 nums.sort((a, b) => a - b)
9 for (let i = 0; i < N - 2; i++) {
10 let j = i + 1
11 let k = N - 1
12 while (j < k) {
13 let sum = nums[i] + nums[j] + nums[k]
14 if (sum === 0) {
15 res.add([nums[i], nums[j], nums[k]].join("|"))
16 j++
17 k--
18 } else if (sum > 0) {
19 k--
20 } else if (sum < 0) {
21 j++
22 }
23 }
24 }
25 return Array.from(res.values()).map(triplet => triplet.split("|").map(Number))
26}

Comments

Loading comments...

Tags

leetcode

array

two pointers

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Merge Sorted Array

HoningJS

Search Posts