-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreeSum.java
More file actions
61 lines (47 loc) · 1.53 KB
/
ThreeSum.java
File metadata and controls
61 lines (47 loc) · 1.53 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
package array;
import java.util.*;
/**
* Description: https://leetcode.com/problems/3sum
* Difficulty: Medium
* Time complexity: O(n^2)
* Space complexity: O(n)
*/
public class ThreeSum {
public List<List<Integer>> threeSumViaTwoPointers(int[] nums) {
Set<List<Integer>> result = new HashSet<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(List.of(nums[i], nums[left], nums[right]));
left++;
right--;
} else if (sum > 0) {
right--;
} else {
left++;
}
}
}
return new ArrayList<>(result);
}
public List<List<Integer>> threeSumWithMemoization(int[] nums) {
Set<List<Integer>> result = new HashSet<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
Set<Integer> seen = new HashSet<>();
for (int j = i + 1; j < nums.length; j++) {
int target = - nums[i] - nums[j];
if (seen.contains(target)) {
result.add(List.of(nums[i], nums[j], target));
} else {
seen.add(nums[j]);
}
}
}
return new ArrayList<>(result);
}
}