# 3 Sum

##### 题目

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.

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

##### 样例

For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

##### 解题思路

``````Arrays.sort();
``````

``````public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);

for (int i = 0; i < nums.length; i++) {
// skip the same result
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1, right = nums.length - 1;
while (left < right) {
List<Integer> temp = new ArrayList<Integer>();
if (nums[left] + nums[right] + nums[i] == 0) {
// skip the same result
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
// skip the same result
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
} else if (nums[left] + nums[right] + nums[i] < 0) {
left++;
} else {
right--;
}
}
}
return res;
}
``````