3Sum

Problem:

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)

Leetcode link
Lintcode link

My Solution:

Sort the list first, which takes O(Nlog N). Then go through the sorted list, for each integer “nums[i]” in the list,
narrow the range from the integers at index i and the end of the list. It takes O(n^2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*************************************************************************
> File Name: ThreeSum.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Wed 11 Nov 18:17:20 2015
************************************************************************/


public class ThreeSum{
public List<List<Integer>> threeSum(int[] nums){
List<List<Integer>> result = new ArrayList<List<Integer>>();

if (nums.length < 3)
return result;

Arrays.sort(nums);

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

int start = i + 1;
int end = nums.length - 1;

while (start < end){
if (nums[i] + nums[start] + nums[end] == 0){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[start]);
list.add(nums[end]);
result.add(list);

start++;
end--;

while (nums[start - 1] == nums[start] && start < end)
start++;

while(nums[end + 1] == nums[end] && start < end)
end--;
} else if (nums[i] + nums[start] + nums[end] < 0){
start++;
} else{
end--;
}
}
}
return result;
}
}

Related Problem:
Two Sum
4Sum
3Sum Closest