# LeetCode 15. 3Sum 三数之和

## 题目

https://leetcode.com/problems/3sum/description/

Given an array S of n integers, are there elements abc 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]
]
```

## 讲解

Three sum是Two Sum的跟进题。

num1 + num2  + num3 = 0

## Java参考代码

```class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> results = new ArrayList<>();

if (nums == null || nums.length < 3) {
return results;
}

Arrays.sort(nums);

for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}

int target = -nums[i];
int left = i + 1;
int right = nums.length - 1;

twoSumHelper(nums, results, target, left, right);
}

return results;
}

private void twoSumHelper(int[] nums, List<List<Integer>> results, int target, int left, int right) {
while (left < right) {
if (nums[left] + nums[right] == target) {
List<Integer> triplet = new ArrayList<>();

left++;
right--;

while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
} else if (nums[left] + nums[right] > target) {
right--;
} else if (nums[left] + nums[right] < target) {
left++;
}
}
}
}```