forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4Sum.java
More file actions
37 lines (32 loc) · 1.15 KB
/
4Sum.java
File metadata and controls
37 lines (32 loc) · 1.15 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
class Solution {
public static List<List<Integer>> fourSum(int[] nums, int target) {
Set<List<Integer>> ans = new HashSet<>();
Arrays.sort(nums);
for (int i=0; i<nums.length; i++) {
for (int j=i+1; j<nums.length; j++) {
int temp = target - (nums[i] + nums[j]);
int start = j+1;
int end = nums.length-1;
while (start < end) {
if (nums[start] + nums[end] == temp) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[start]);
list.add(nums[end]);
ans.add(list);
start++;
end--;
}
else if (nums[start] + nums[end] < temp) {
start++;
}
else if (nums[start] + nums[end] > temp) {
end--;
}
}
}
}
return new ArrayList<>(ans);
}
}