-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreeSum.java
64 lines (58 loc) · 1.92 KB
/
ThreeSum.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class ThreeSum {
public static void main(String[] args) {
String a="20.90";
System.out.println(Double.valueOf(a)*100);
int arr[] = {-1, 0, 1, 2, -1, -4};
Arrays.sort(arr);
int splitPos = splitTwo(arr);
if (splitPos > 0) {
int negArr[] = Arrays.copyOfRange(arr, 0, splitPos);
int posArr[] = Arrays.copyOfRange(arr,splitPos, arr.length );
threeSum(negArr, posArr);
}
}
public static void threeSum(int[] neg, int[] pos) {
List<List<Integer>> output = new ArrayList<>();
int res = 0;
int k = pos.length-1;
for (int i = 0, j = i + 1; j < neg.length; i++,j++) {
res = neg[i] + neg[j];
while (k>=0 && pos[k] >= Math.abs(res)) {
if (Math.abs(res) == pos[k]) {
List<Integer> list1 = new ArrayList<>();
list1.add(neg[i]);
list1.add(neg[j]);
list1.add(pos[k]);
output.add(list1);
}
k--;
}
}
k=neg.length-1;
for (int i = 0, j = i + 1; j < pos.length; i++,j++) {
res = pos[i] + pos[j];
while (k>=0 && Math.abs(neg[k]) <= res) {
if (res == Math.abs(neg[k])) {
List<Integer> list2 = new ArrayList<>();
list2.add(pos[i]);
list2.add(pos[j]);
list2.add(neg[k]);
output.add(list2);
}
k--;
}
}
}
public static int splitTwo(int arr[]) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= 0) {
return i;
}
}
return 0;
}
}