- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathSecondMinMax.java
60 lines (50 loc) · 2.08 KB
/
SecondMinMax.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
packagecom.thealgorithms.maths;
importjava.util.function.BiPredicate;
publicfinalclassSecondMinMax {
/**
* Utility class for finding second maximum or minimum based on BiPredicate
* @exception IllegalArgumentException => if input array is of length less than 2 also if all elements are same
* @return the second minimum / maximum value from the input array
* @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT )
*/
privateSecondMinMax() {
}
privatestaticintsecondBest(finalint[] arr, finalintinitialVal, finalBiPredicate<Integer, Integer> isBetter) {
checkInput(arr);
intbest = initialVal;
intsecBest = initialVal;
for (finalintnum : arr) {
if (isBetter.test(num, best)) {
secBest = best;
best = num;
} elseif ((isBetter.test(num, secBest)) && (num != best)) {
secBest = num;
}
}
checkOutput(secBest, initialVal);
returnsecBest;
}
/**
* @brief Finds the Second minimum / maximum value from the array
* @param arr the input array
* @exception IllegalArgumentException => if input array is of length less than 2 also if all elements are same
* @return the second minimum / maximum value from the input array
* @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT )
*/
publicstaticintfindSecondMin(finalint[] arr) {
returnsecondBest(arr, Integer.MAX_VALUE, (a, b) -> a < b);
}
publicstaticintfindSecondMax(finalint[] arr) {
returnsecondBest(arr, Integer.MIN_VALUE, (a, b) -> a > b);
}
privatestaticvoidcheckInput(finalint[] arr) {
if (arr.length < 2) {
thrownewIllegalArgumentException("Input array must have length of at least two");
}
}
privatestaticvoidcheckOutput(finalintsecNum, finalintinitialVal) {
if (secNum == initialVal) {
thrownewIllegalArgumentException("Input array should have at least 2 distinct elements");
}
}
}