Problem: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
Solution: I will bring up one example solution for this problem.
Idea:
We will use two pointer for this problem but first we have to sort this array because two pointer works perfectly when this array is sort.
First, we declare a variable i, start from 0 and end at nums.length-2 because the result return an integer array of 3 so i have to start from 0 and end at 2. and declare variable j and k with j equal to i +1 and k equa to nums.length - 1.
i value only smaller than 0.Second, create a loop when every j smaller than k. If sum = nums[i] + nums[j] + nums[k] === 0 we push result to an result array.
Then we move j up and move k down by using j++ and k --.
If sum < 0, we move j up (j++)
if sum > 0 we move k down (k--)
if the next number of j - nums[j+1] === nums[j] we skip that nums by move j up (j++) and do the same things with k by move k down (k--)
Continue to the end of loop and return result.
let threeSum = function (nums) { const result = []; if (nums.length < 3) return results; nums = nums.sort((a, b) => a - b); let target = 0; for (let i = 0; i < nums.length - 2; i++) { if (i > 0 && nums[i] === nums[i-1)) continue if (nums[i] > target) break let j = i+1; k = nums.length - 1; while (j < k) { let sum = nums[i] + nums[j] + nums[k] if (sum === target) { result.push([nums[i], nums[j], nums[k]); while (nums[j] === nums[j+1]) j++ while (nums[k] === nums[k-1]) k-- j++; k--; } else if (sum < target) { j++ } else { k-- } } } }