-
Notifications
You must be signed in to change notification settings - Fork 0
/
secondLargest,smallest
44 lines (36 loc) · 1.13 KB
/
secondLargest,smallest
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
public class Solution {
public static int secondLargest(int n, int[] a) {
int largest = a[0];
int slargest = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (a[i] > largest) {
slargest = largest;
largest = a[i];
} else if (slargest < a[i] && largest > a[i]) {
slargest = a[i];
}
}
return slargest;
}
public static int secondSmallest(int n, int[] a) {
int smallest = a[0];
int ssmallest = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (a[i] < smallest) {
ssmallest = smallest;
smallest = a[i];
} else if (ssmallest > a[i] && a[i] != smallest) {
ssmallest = a[i];
}
}
return ssmallest;
}
public static int[] getSecondOrderElements(int n, int[] a) {
if (n < 2) {
return new int[]{-1, -1};
}
int secondLarge = secondLargest(n, a);
int secondSmall = secondSmallest(n, a);
return new int[]{secondLarge, secondSmall};
}
}