forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSum0.java
More file actions
77 lines (66 loc) · 1.96 KB
/
ThreeSum0.java
File metadata and controls
77 lines (66 loc) · 1.96 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package TwoPointers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* Author - archit.s
* Date - 16/10/18
* Time - 11:54 AM
*/
public class ThreeSum0 {
public ArrayList<ArrayList<Integer>> threeSum(ArrayList<Integer> A) {
ArrayList<ArrayList<Integer>> r = new ArrayList<>();
Collections.sort(A);
int i = 0;
while(i<A.size()-2){
int j=i+1;
int k = A.size()-1;
while(j<k){
int temp = A.get(i) + A.get(j) + A.get(k);
if(temp == 0){
ArrayList<Integer> t = new ArrayList<>();
t.add(A.get(i));
t.add(A.get(j));
t.add(A.get(k));
r.add(t);
while(A.get(j).equals(A.get(j+1))){
j++;
if(j==A.size()-1){
break;
}
}
j++;
}
else if(temp > 0){
while(A.get(k).equals(A.get(k-1))){
k--;
if(k==0){
break;
}
}
k--;
}
else{
while(A.get(j).equals(A.get(j+1))){
j++;
if(j==A.size()-1){
break;
}
}
j++;
}
}
while(A.get(i).equals(A.get(i+1))){
i++;
if(i==A.size()-1){
return r;
}
}
i++;
}
return r;
}
public static void main(String[] args) {
System.out.println(new ThreeSum0().threeSum(new ArrayList<>(Arrays.asList( -4, 2, -1, 1, -4, 2, -5, -3, 2 ))));
}
}