### 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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)

``````import java.util.*;

/**
* Created by gzdaijie on 16/5/11
* 先排序,后遍历
* 遍历过程中,遇到每个元素,就检测其后面的每2个元素之和与之相加是否为0
* 如何避免重复? 遍历下一个元素时,确保这个元素与上一个元素不同即可
* 例如 -1,-1,-1,1,1,2,第一次是-1, 那么第二次就是 1
* 时间复杂度O(N * lgN + N * N) => O(N * N)
*/
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);

int left, right, sum;
ArrayList<Integer> triplets;

for (int i = 0; i < nums.length - 2; i++) {
if (i != 0) {
// 为避免重复,i需要增加到与上次不同
while (nums[i - 1] == nums[i] && i < nums.length - 2) ++i;
}
left = i + 1;
right = nums.length - 1;

while (left < right) {
sum = nums[i] + nums[left] + nums[right];

if (sum == 0) {
triplets = new ArrayList<>();
++left;
// 避免后2个数重复,left需增加到与之前不同为止
while (left < right && nums[left - 1] == nums[left]) ++left;
} else if (sum > 0) {
--right;
} else {
++left;
}
}
}
return result;
}
}
``````
updated 2016-05-11 22:37:50