Skip to content

Commit b01bbf1

Browse files
Create FourSumProblem.java
1 parent e499d3b commit b01bbf1

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.thealgorithms.misc;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class FourSumProblem {
8+
public List<List<Integer>> fourSum(int[] nums, int target) {
9+
10+
int n = nums.length;
11+
List<List<Integer>> ans = new ArrayList<>();
12+
Arrays.sort(nums);
13+
14+
for (int i = 0; i < n; i++) {
15+
if (i > 0 && nums[i] == nums[i - 1]) continue;
16+
17+
for (int j = i + 1; j < n; j++) {
18+
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
19+
20+
int k = j + 1;
21+
int l = n - 1;
22+
23+
while (k < l) {
24+
long sum = (long) nums[i] + nums[j] + nums[k] + nums[l];
25+
26+
if (sum == target) {
27+
ans.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
28+
k++;
29+
l--;
30+
31+
while (k < l && nums[k] == nums[k - 1]) k++;
32+
while (k < l && nums[l] == nums[l + 1]) l--;
33+
} else if (sum < target) {
34+
k++;
35+
} else {
36+
l--;
37+
}
38+
}
39+
}
40+
}
41+
return ans;
42+
}
43+
}

0 commit comments

Comments
 (0)