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]
  2. Output: [[-1,-1,2],[-1,0,1]]
  1. Input: nums = []
  2. Output: []
  1. Input: nums = [0]
  2. Output: []

Constraints

  • 0 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

Solution

  1. var threeSum = function (nums) {
  2. if (nums.length < 3) return [];
  3. nums.sort((pre, next) => pre - next);
  4. const res = [];
  5. for (let i = 0; i < nums.length; i++) {
  6. if (i === 0 || nums[i] !== nums[i - 1]) {
  7. const d = -nums[i];
  8. let a = i + 1, b = nums.length - 1;
  9. const numMap = new Map();
  10. while (a < b) {
  11. if (nums[a] + nums[b] > d) {
  12. b--;
  13. } else if (nums[a] + nums[b] < d) {
  14. a++;
  15. } else {
  16. const v = numMap.get(nums[a]);
  17. if (!v) {
  18. numMap.set(nums[a], [nums[b]]);
  19. } else if (!v.includes(nums[b])) {
  20. v.push(nums[b]);
  21. }
  22. a++;
  23. b--;
  24. }
  25. }
  26. numMap.forEach((value, key) => {
  27. for (let j = 0; j < value.length; j++) {
  28. res.push([nums[i], key, value[j]]);
  29. }
  30. });
  31. }
  32. }
  33. return res;
  34. };