-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
49 lines (42 loc) · 1.26 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package org.example.problems._3sum;
import org.example.problems.SolutionInterface;
import java.util.*;
public class Solution implements SolutionInterface {
@Override
public String getName() {
return "3Sum";
}
@Override
public String getUrl() {
return "https://leetcode.com/problems/3sum/";
}
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Set<List<Integer>> set = new HashSet<>();
for (int i = 0; i < nums.length - 2; i++) {
int first = nums[i];
if (first > 0) {
break;
}
int middleIndex = i + 1;
int lastIndex = nums.length - 1;
while (middleIndex < lastIndex) {
int middle = nums[middleIndex];
int last = nums[lastIndex];
if (last < 0) {
break;
}
int sum = first + middle + last;
if (sum == 0) {
set.add(List.of(first, middle, last));
}
if (sum > 0) {
lastIndex--;
} else {
middleIndex++;
}
}
}
return new ArrayList<>(set);
}
}