-
Notifications
You must be signed in to change notification settings - Fork 0
/
3sum
41 lines (41 loc) · 1.39 KB
/
3sum
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
import java.util.AbstractList;
class Solution {
private List<List<Integer>> res;
public List<List<Integer>> threeSum(int[] nums) {
int target = 0;
return new AbstractList<List<Integer>>() {
public List<Integer> get(int index) {
init();
return res.get(index);
}
public int size() {
init();
return res.size();
}
private void init() {
if (res != null) return;
Arrays.sort(nums);
int l, r;
int sum;
Set<List<Integer>> tempRes = new HashSet<>();
for (int i = 0; i < nums.length - 2; ++i) {
l = i + 1;
r = nums.length - 1;
while (l < r) {
sum = nums[i] + nums[l] + nums[r];
if (sum == target) {
List<Integer> t = new ArrayList<>();
t.add(nums[i]);
t.add(nums[l]);
t.add(nums[r]);
tempRes.add(t);
}
if (sum < target) ++l;
else --r;
}
}
res = new ArrayList<List<Integer>>(tempRes);
}
};
}
}