-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path_15_3Sum.java
36 lines (29 loc) · 929 Bytes
/
_15_3Sum.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
package io.github.tahanima.leetcode;
import java.util.*;
/**
* @author tahanima
*/
public class _15_3Sum {
public List<List<Integer>> threeSum(int[] nums) {
HashSet<ArrayList<Integer>> hs = new HashSet<>();
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int num = -(nums[i] + nums[j]);
if (j == (n - 1)) {
continue;
}
if (Arrays.binarySearch(nums, j + 1, n, num) >= 0) {
ArrayList<Integer> triplet = new ArrayList<>();
triplet.add(nums[i]);
triplet.add(nums[j]);
triplet.add(num);
Collections.sort(triplet);
hs.add(triplet);
}
}
}
return new ArrayList<>(hs);
}
}