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.
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
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.
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
The simplest approach is to try every possible triplet in the array and check if their sum is zero. Although this guarantees we find all solutions, it is not efficient.
The two-pointers approach is more efficient. By sorting the array and using two pointers, we reduce the time complexity significantly.
i.i, initialize two pointers: left at i+1 and right at the end of the array.i, left, and right.left pointer to increase the sum.right pointer to decrease the sum.