forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUjoonnee.java
More file actions
87 lines (73 loc) · 2.16 KB
/
Ujoonnee.java
File metadata and controls
87 lines (73 loc) · 2.16 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Set<List<Integer>> set = new HashSet<>();
for(int i = 0; i < nums.length && nums[i] <= 0; i++) {
int j = i+1;
int k = nums.length - 1;
while(j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum > 0) {
k--;
continue;
}
if (sum < 0) {
j++;
continue;
}
set.add(List.of(nums[i], nums[j], nums[k]));
j++;
k--;
}
}
return new ArrayList<>(set);
}
}
/*
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
Set<Triplet> set = new HashSet<>();
for(int i = 0; i < nums.length; i++) {
int target = -nums[i];
for(int j = i+1; j < nums.length; j++) {
int operand = target - nums[j];
if (map.containsKey(operand) && map.get(operand) > j) {
set.add(new Triplet(nums[i], nums[j], operand));
}
}
}
return set.stream().map(t -> List.of(t.triplet[0], t.triplet[1], t.triplet[2])).collect(Collectors.toList());
}
}
class Triplet {
int[] triplet;
Triplet(int first, int second, int third) {
this.triplet = new int[] { first, second, third };
Arrays.sort(triplet);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Triplet that)) {
return false;
}
for(int i = 0; i<3; i++) {
if (this.triplet[i] != that.triplet[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(triplet[0], triplet[1], triplet[2]);
}
}
*/