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