Skip to content

Commit 01c7d2c

Browse files
authored
Update 3Sum.java
1 parent 2f1c3ee commit 01c7d2c

File tree

1 file changed

+13
-20
lines changed

1 file changed

+13
-20
lines changed

Medium/3Sum.java

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,22 @@
11
class Solution {
22
public List<List<Integer>> threeSum(int[] nums) {
33
Arrays.sort(nums);
4-
List<List<Integer>> list = new ArrayList<>();
4+
List<List<Integer>> result = new ArrayList<>();
55
for (int i = 0; i < nums.length && nums[i] <= 0; i++) {
66
if (i == 0 || nums[i - 1] != nums[i]) {
7-
twoSumHelper(nums, i, list);
8-
}
9-
}
10-
return list;
11-
}
12-
13-
private void twoSumHelper(int[] nums, int i, List<List<Integer>> list) {
14-
int low = i + 1;
15-
int high = nums.length - 1;
16-
while (low < high) {
17-
int sum = nums[i] + nums[low] + nums[high];
18-
if (sum < 0 || (low > i + 1 && nums[low] == nums[low - 1])) {
19-
low++;
20-
}
21-
else if (sum > 0 || (high < nums.length - 1 && nums[high] == nums[high + 1])) {
22-
high--;
23-
}
24-
else {
25-
list.add(Arrays.asList(nums[i], nums[low++], nums[high--]));
7+
Set<Integer> set = new HashSet<>();
8+
for (int j = i + 1; j < nums.length; j++) {
9+
int target = -1 * (nums[i] + nums[j]);
10+
if (set.contains(target)) {
11+
result.add(Arrays.asList(nums[i], nums[j], target));
12+
while (j + 1 < nums.length && nums[j] == nums[j + 1]) {
13+
j++;
14+
}
15+
}
16+
set.add(nums[j]);
17+
}
2618
}
2719
}
20+
return result;
2821
}
2922
}

0 commit comments

Comments
 (0)