-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathThreeSum.java
59 lines (39 loc) · 1.28 KB
/
ThreeSum.java
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
50
51
52
53
54
55
56
57
58
59
import java.util.*;
/**
* Created by achoudhary on 26/01/2016.
*/
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums.length < 3)
return result;
Arrays.sort(nums);
Set<List<Integer>> proxy = new HashSet<>();
for (int i = 0; i < nums.length-2; i++) {
if(i ==0 || nums[i] > nums[i-1]) {
int target = -nums[i];
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
if (nums[start] + nums[end] == target) {
List<Integer> value = new ArrayList<>();
value.add(nums[i]);
value.add(nums[start]);
value.add(nums[end]);
proxy.add(value);
start++;
end--;
} else if (nums[start] + nums[end] > target) {
end--;
} else {
start++;
}
}
}
}
result.addAll(proxy);
return result;
}
public static void main(String[] args) {
}
}