Leetcode Practice
LC 3. 3Sum
- Last updated
- Reading time
- 1 min read
The problem
First Solution
function threeSum(nums: number[]): number[][] {
nums = nums.sort((a, b) => a - b)
let answer = []
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) {
continue
}
let leftPointer = i + 1
let rightPointer = nums.length - 1
while (leftPointer < rightPointer) {
let sum = nums[leftPointer] + nums[i] + nums[rightPointer]
if (sum === 0) {
answer.push([nums[i], nums[leftPointer], nums[rightPointer]])
while (leftPointer < rightPointer && nums[leftPointer] === nums[leftPointer + 1]) {
leftPointer++
}
while (leftPointer < rightPointer && nums[rightPointer] === nums[rightPointer - 1]) {
rightPointer--
}
leftPointer++
rightPointer--
} else if (sum > 0) {
rightPointer--
} else if (sum < 0) {
leftPointer++
}
}
}
return answer
}