# 3 Sum

## Question

### Problem Statement

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]
]


## 题解1 - 排序 + 哈希表 + 2 Sum

### Python

class Solution:
"""
@param numbersbers : Give an array numbersbers of n integer
@return : Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
triplets = []
length = len(numbers)
if length < 3:
return triplets

numbers.sort()
for i in xrange(length):
target = 0 - numbers[i]
# 2 Sum
hashmap = {}
for j in xrange(i + 1, length):
item_j = numbers[j]
if (target - item_j) in hashmap:
triplet = [numbers[i], target - item_j, item_j]
if triplet not in triplets:
triplets.append(triplet)
else:
hashmap[item_j] = j

return triplets


### 源码分析

1. 异常处理，对长度小于3的直接返回。
2. 排序输入数组，有助于提高效率和返回有序列表。
3. 循环遍历排序后数组，先取出一个元素，随后求得 2 Sum 中需要的目标数。
4. 由于本题中最后返回结果不能重复，在加入到最终返回值之前查重。

### C++

class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num)
{
vector<vector<int> > result;
if (num.size() < 3) return result;

int ans = 0;

sort(num.begin(), num.end());

for (int i = 0;i < num.size() - 2; ++i)
{
if (i > 0 && num[i] == num[i - 1])
continue;
int j = i + 1;
int k = num.size() - 1;

while (j < k)
{
ans = num[i] + num[j] + num[k];

if (ans == 0)
{
result.push_back({num[i], num[j], num[k]});
++j;
while (j < num.size() && num[j] == num[j - 1])
++j;
--k;
while (k >= 0 && num[k] == num[k + 1])
--k;
}
else if (ans > 0)
--k;
else
++j;
}
}

return result;
}
};


### Java

public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
// Assumptions: array is not null, array.length >= 3
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int tmp = nums[left] + nums[right];
if (tmp + nums[i] == 0) {
left++;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
} else if (tmp + nums[i] < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
}


### 源码分析

S = {-1 0 1 2 -1 -4}

S = {-4 -1 -1 0 1 2}
↑  ↑        ↑
i  j        k
→        ←
i每轮只走一步，j和k根据S[i]+S[j]+S[k]=ans和0的关系进行移动，且j只向后走（即S[j]只增大），k只向前走（即S[k]只减小）