Skip to content

Commit 8634d8a

Browse files
committed
Java solution 18
1 parent f483351 commit 8634d8a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

java/_0184Sum.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import java.util.*;
2+
3+
/**
4+
* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
5+
* <p>
6+
* Note: The solution set must not contain duplicate quadruplets.
7+
* <p>
8+
* For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
9+
* A solution set is:
10+
* [
11+
* [-1, 0, 0, 1],
12+
* [-2, -1, 1, 2],
13+
* [-2, 0, 0, 2]
14+
* ]
15+
* <p>
16+
* Created by drfish on 6/20/2017.
17+
*/
18+
public class _0184Sum {
19+
public List<List<Integer>> fourSum(int[] nums, int target) {
20+
List<List<Integer>> result = new ArrayList<>();
21+
if (nums.length < 4) {
22+
return result;
23+
}
24+
Arrays.sort(nums);
25+
for (int i = 0; i < nums.length - 3; i++) {
26+
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
27+
break;
28+
}
29+
if (nums[i] + nums[nums.length - 1] + nums[nums.length - 2] + nums[nums.length - 3] < target) {
30+
continue;
31+
}
32+
if (i > 0 && nums[i] == nums[i - 1]) {
33+
continue;
34+
}
35+
36+
for (int j = i + 1; j < nums.length - 2; j++) {
37+
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
38+
break;
39+
}
40+
if (nums[i] + nums[j] + nums[nums.length - 1] + nums[nums.length - 2] < target) {
41+
continue;
42+
}
43+
if (j > i + 1 && nums[j] == nums[j - 1]) {
44+
continue;
45+
}
46+
47+
int low = j + 1, high = nums.length - 1;
48+
while (low < high) {
49+
int sum = nums[i] + nums[j] + nums[low] + nums[high];
50+
if (sum == target) {
51+
result.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high]));
52+
while (low < high && nums[low] == nums[low + 1]) {
53+
low++;
54+
}
55+
while (low < high && nums[high] == nums[high - 1]) {
56+
high--;
57+
}
58+
low++;
59+
high--;
60+
} else if (sum < target) {
61+
low++;
62+
} else {
63+
high--;
64+
}
65+
}
66+
}
67+
}
68+
return result;
69+
}
70+
}

0 commit comments

Comments
 (0)