Skip to content

Commit 59479e8

Browse files
committed
Add Solution2.java to problems 18
1 parent f12fa94 commit 59479e8

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

solution/0018.4Sum/Solution2.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public List<List<Integer>> fourSum(int[] nums, int target) {
3+
if (nums.length < 4) {
4+
return new ArrayList<>();
5+
}
6+
Arrays.sort(nums);
7+
8+
List<List<Integer>> results = new ArrayList<>();
9+
10+
for (int i = 0; i < nums.length; i++) {
11+
for (int j = i + 1; j < nums.length; j++) {
12+
int low = j + 1, high = nums.length - 1;
13+
int sub = target - nums[i] - nums[j];
14+
while (low < high) {
15+
if (nums[low] + nums[high] < sub) {
16+
low++;
17+
} else if (nums[low] + nums[high] > sub) {
18+
high--;
19+
} else {
20+
results.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high]));
21+
low++;
22+
high--;
23+
}
24+
}
25+
}
26+
}
27+
28+
return results.stream().distinct().collect(Collectors.toList());
29+
}
30+
}

0 commit comments

Comments
 (0)