-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3Sum.java
More file actions
31 lines (29 loc) · 932 Bytes
/
3Sum.java
File metadata and controls
31 lines (29 loc) · 932 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
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] arr) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(arr);
int n=arr.length;
for (int i = 0; i < n; i++) {
if (i != 0 && arr[i] == arr[i - 1]) continue;
int j = i + 1;
int k = n - 1;
while (j < k) {
int sum = arr[i] + arr[j] + arr[k];
if (sum < 0) {
j++;
} else if (sum > 0) {
k--;
} else {
List<Integer> temp = Arrays.asList(arr[i], arr[j], arr[k]);
ans.add(temp);
j++;
k--;
while (j < k && arr[j] == arr[j - 1]) j++;
while (j < k && arr[k] == arr[k + 1]) k--;
}
}
}
return ans;
}
}