-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode15.java
More file actions
63 lines (55 loc) · 2.29 KB
/
LeetCode15.java
File metadata and controls
63 lines (55 loc) · 2.29 KB
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
60
61
62
63
import java.util.List;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Arrays;
import util.PrintUtil;
public class LeetCode15 {
public static void main(String[] args) {
// 输入:nums = [-1,0,1,2,-1,-4]
// 输出:[[-1,-1,2],[-1,0,1]]
PrintUtil.printNestedList(new Solution15().threeSum(new int[] { -1, 0, 1, 2,
-1, -4 }));
// 输入:nums = [0,1,1]
// 输出:[]
PrintUtil.printNestedList(new Solution15().threeSum(new int[] { 0, 1, 1 }));
// 输入:nums = [0,0,0]
// 输出:[[0,0,0]]
PrintUtil.printNestedList(new Solution15().threeSum(new int[] { 0, 0, 0 }));
// 输入:nums = [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]
// 输出:[[-5,1,4],[-4,0,4],[-4,1,3],[-2,-2,4],[-2,1,1],[0,0,0]]
PrintUtil.printNestedList(
new Solution15().threeSum(new int[] { -4, -2, 1, -5, -4, -4, 4, -2, 0, 4, 0,
-2, 3, 1, -5, 0 }));
// 输入:nums = [-5,0,-2,3,-2,1,1,3,0,-5,3,3,0,-1]
// 输出:[[-2,-1,3],[-2,1,1],[-1,0,1],[0,0,0]]
PrintUtil.printNestedList(
new Solution15().threeSum(new int[] { -5, 0, -2, 3, -2, 1, 1, 3, 0, -5, 3, 3, 0, -1 }));
}
}
class Solution15 {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
HashSet<Integer> seconds = new HashSet<Integer>();
HashSet<String> records = new HashSet<>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (seconds.contains(0 - nums[i] - nums[j])) {
List<Integer> list = List.of(nums[i], 0 - nums[i] - nums[j], nums[j]);
// NOTE: 去重很重要
String s = String.format("%d|%d|%d", nums[i], 0 - nums[i] - nums[j], nums[j]);
if (!records.contains(s)) {
result.add(list);
records.add(s);
}
}
seconds.add(nums[j]);
}
seconds.clear();
}
return result;
}
}