-
-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathThreeSum.java
More file actions
40 lines (30 loc) · 915 Bytes
/
Copy pathThreeSum.java
File metadata and controls
40 lines (30 loc) · 915 Bytes
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
package leetcode.medium;
import java.util.*;
public class ThreeSum {
List<List<Integer>> threeSum(int[] arr) {
if (arr == null || arr.length < 3) return new ArrayList<>();
// Sort the elements
Arrays.sort(arr);
Set<List<Integer>> result = new HashSet<>();
// Now fix the first element and find the other two elements
for (int i = 0; i < arr.length - 2; i++)
{
// Find other two elements using Two Sum approach
int left = i + 1;
int right = arr.length - 1;
while (left < right) {
int sum = arr[i] + arr[left] + arr[right];
if (sum == 0) {
// Add the set, and move to find other triplets
result.add(Arrays.asList(arr[i], arr[left], arr[right]));
left++;
right--;
} else if (sum < 0)
left++;
else
right--;
}
}
return new ArrayList<>(result);
}
}