Links:
Leetcode-cn.com/problems/3s…
Train of thought
/* * * 1. First sort, then again array, with I as the first reference point * 2. I < nums.length - 2, because 1, 2, 3, 4, if 2 as the basis point, then sure behind only possible 3, 4, otherwise gather enough 3 numbers * 3. For example, when the base point is 1, the double pointer points to 2 and 4, continuously shrinking, if the base point + pointer start + pointer end < 0, then represents the need for a * larger number, then is the start ++ pointer, instead is the end --, if already and 0, So push into the result array, start ++, end --; -5222333 (-5, 2, 3) start ++ end (-5, 2, 3) end (-5, 2, 3) So we need start all the way to ++ and end all the way to --, until the last start is not equal to the next start, and end is the same; * 5. After the traversal of I, we enter the next I, so we need to judge whether the value of this I is the same as the value of the last I, because if it is the same, such as -1, -1, 1, 0 *, then there will be repeated -1, 1, 0 two results, * */ var threeSum = function(nums) {if (nums.length < 3) return []; let ret = []; nums.sort((a, b) => a - b); for (let i = 0; i < nums.length - 2; i++) { let start = i + 1; let end = nums.length - 1; if (i > 0 && nums[i] === nums[i - 1]) continue; while (start < end) { if (nums[i] + nums[start] + nums[end] < 0) { start ++; } else if (nums[i] + nums[start] + nums[end] > 0) { end --; } else { ret.push([nums[i], nums[start], nums[end]]); start ++; end --; while (start < end && nums[start] === nums[start - 1]) start ++; while (start < end && nums[end] === nums[end + 1]) end --; } } } return ret; }; The console. The log (threeSum ([1, 2, 1, 4]))Copy the code