-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathThreeSum.java
58 lines (42 loc) · 1003 Bytes
/
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
package leetcode;
import java.util.*;
/**
* Created by nikoo28 on 7/9/19 1:18 AM
*/
class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Set<List<Integer>> solution = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
findSum(nums, 0 - nums[i], i, solution);
}
return new ArrayList<>(solution);
}
private void findSum(int[] arr, int sum, int ignore, Set<List<Integer>> solution) {
int i = 0;
int end = arr.length - 1;
while (i < end) {
if (i == ignore) {
i++;
continue;
}
if (end == ignore) {
end--;
continue;
}
if (arr[i] + arr[end] == sum) {
List<Integer> set = new ArrayList<>();
set.add(arr[ignore]);
set.add(arr[i]);
set.add(arr[end]);
Collections.sort(set);
solution.add(set);
}
if (arr[i] + arr[end] > sum) {
end--;
continue;
}
i++;
}
}
}