-
Notifications
You must be signed in to change notification settings - Fork 688
/
FindPythagoreanTriplets.java
83 lines (66 loc) · 1.94 KB
/
FindPythagoreanTriplets.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package math;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class FindPythagoreanTriplets {
/*
* Given an integer array find all Pythagorean triplets (a^2 + b^2 = c^2).
* Input: 4, 16, 1, 2, 3, 5, 6, 8, 25, 10
*
* the Pythagorean triplets are (3, 4, 5) and (6, 8, 10) as
* 32 + 42 = 52 and 62 + 82 = 102
*
* Runtime Complexity:
* Quadratic, O(n2)
*
* Memory Complexity:
* Constant, O(1).
*
*
* */
protected static List<int[]> findPythagoreanTriplets(int[] arr) {
int n = arr.length;
List<int[]> triplets = new ArrayList<int[]>();
Arrays.sort(arr);
for (int i = 0; i < n; ++i) {
if (arr[i] == 0) continue;
int c2 = arr[i] * arr[i];
int j = 0;
int k = n - 1;
while (j < k) {
if (j == i || arr[j] == 0) {
j += 1;
continue;
}
if (k == i || arr[k] == 0) {
k -= 1;
continue;
}
int a2 = arr[j] * arr[j];
int b2 = arr[k] * arr[k];
if (a2 + b2 == c2) {
triplets.add(
new int[]{arr[i], arr[j], arr[k]});
break;
} else if (a2 + b2 + (-c2) > 0) {
k -= 1;
} else {
j += 1;
}
}
}
return triplets;
}
public static void main(String[] argv) {
int[] l2 = {13, 4, 25, 6, 8, 110, 99, 32, 15, 18, 19};
List<int[]> t2 = findPythagoreanTriplets(l2);
System.out.println("***********");
for (int[] a : t2) {
for (int x : a) {
System.out.print(x + ", ");
}
System.out.println();
}
}
}