-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.java
More file actions
38 lines (34 loc) · 1.05 KB
/
3Sum.java
File metadata and controls
38 lines (34 loc) · 1.05 KB
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
import java.util.* ;
import java.io.*;
public class Solution {
public static ArrayList<ArrayList<Integer>> findTriplets(int[] arr, int n, int K) {
// Write your code here.
Set<ArrayList<Integer>> ans = new HashSet<>();
Arrays.sort(arr);
for(int i=0;i<arr.length;i++){
int j=i+1;
int l=arr.length-1;
int sum= K-arr[i];
while(j<l){
if(arr[j]+arr[l]==sum){
ArrayList<Integer> temp = new ArrayList<>();
temp.add(arr[i]);
temp.add(arr[j]);
temp.add(arr[l]);
ans.add(new ArrayList(temp));
l--;
while(l>=0 && arr[l]==arr[l+1]){
l--;
}
}
else if( arr[j]+arr[l]>sum){
l--;
}
else{
j++;
}
}
}
return new ArrayList(ans);
}
}