# leetcode #15 3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

``````For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
``````
• 题目大意
给定一组整数，找到数组中所有相加等于0的3个数，结果中不能有相同的一组。

``````/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
nums.sort((a, b) => a - b);
const result = [];
console.log(nums);
for (let i = 0; i < nums.length - 2; i++) {
if (nums[i] === nums[i - 1]) { // 跳过相同的值
continue;
}
let j = i + 1;
let k = nums.length - 1;
const rest = -nums[i];
while (j < k) {
if (nums[j] + nums[k] === rest) {
result.push([nums[i], nums[j], nums[k]]);
while (j < k && nums[j] === nums[j + 1]) j++; // 跳过相同的值
while (j < k && nums[k] === nums[k - 1]) k--;
j++;
k--;
} else if (nums[j] + nums[k] > rest) k--; // 如果两数相加比剩余的值大，减小较大的值
else {
j++; // 否则增加较小的值
}
}
}
return result;
};
``````