-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.3-sum.java
More file actions
30 lines (27 loc) · 938 Bytes
/
Copy path15.3-sum.java
File metadata and controls
30 lines (27 loc) · 938 Bytes
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
/*
* @lc app=leetcode id=15 lang=java
*
* [15] 3Sum
*/
// @lc code=start
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
Set<Integer> dups = new HashSet<>();
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; ++i)
if (dups.add(nums[i])) {
for (int j = i + 1; j < nums.length; ++j) {
int complement = -nums[i] - nums[j];
if (seen.containsKey(complement) && seen.get(complement) == i) {
List<Integer> triplet = Arrays.asList(nums[i], nums[j], complement);
Collections.sort(triplet);
res.add(triplet);
}
seen.put(nums[j], i);
}
}
return new ArrayList(res);
}
}
// @lc code=end