Skip to content

Commit 70862f9

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 15_Three_Sum.java
1 parent 53494ff commit 70862f9

File tree

1 file changed

+28
-18
lines changed

1 file changed

+28
-18
lines changed

Two Pointers/15_Three_Sum.java

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,41 @@
11
class Solution {
22
public List<List<Integer>> threeSum(int[] nums) {
3-
if (nums == null || nums.length < 3) {
3+
if (nums == null || nums.length == 0) {
44
return Collections.emptyList();
55
}
66

7-
Set<List<Integer>> result = new HashSet<>();
8-
97
Arrays.sort(nums);
108

9+
List<List<Integer>> result = new ArrayList<>();
10+
1111
for (int i = 0; i < nums.length - 2; i++) {
12-
int j = i + 1, k = nums.length - 1;
13-
14-
while (j < k) {
15-
int sum = nums[i] + nums[j] + nums[k];
16-
17-
if (sum == 0) {
18-
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
19-
j++;
20-
k--;
21-
} else if (sum < 0) {
22-
j++;
23-
} else {
24-
k--;
12+
if (i == 0 || nums[i] != nums[i - 1]) {
13+
int j = i + 1, k = nums.length - 1;
14+
15+
while (j < k) {
16+
int sum = nums[i] + nums[j] + nums[k];
17+
18+
if (sum == 0) {
19+
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
20+
21+
while (j < k && nums[j] == nums[j + 1]) {
22+
++j;
23+
}
24+
while (j < k && nums[k] == nums[k - 1]) {
25+
--k;
26+
}
27+
28+
++j;
29+
--k;
30+
} else if (sum < 0) {
31+
++j;
32+
} else {
33+
--k;
34+
}
2535
}
2636
}
2737
}
2838

29-
return new ArrayList<>(result);
39+
return result;
3040
}
31-
}
41+
}

0 commit comments

Comments
 (0)