-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathApp.java
64 lines (51 loc) · 1.75 KB
/
App.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.util.Arrays;
public class App {
public static Integer findSecondSmallestItem(Integer[] arr) {
if (arr.length <= 1) {
return null;
} else {
Arrays.sort(arr);
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] != arr[i + 1]) {
return arr[i + 1];
}
}
return null;
}
}
public static Integer findSecondSmallestItem2 (Integer[] arr) {
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++){
int current = arr[i];
if (current < smallest){
secondSmallest = smallest;
smallest = current;
}else if(current < secondSmallest && current != smallest){
secondSmallest = current;
}
}
if (secondSmallest == Integer.MAX_VALUE) {
return null;
}
return secondSmallest;
}
public static void main(String args[]) {
Integer[] arr = new Integer[] { 5, 8, 3, 2, 6 };
System.out.println(findSecondSmallestItem(arr));
Integer[] arr2 = new Integer[] { 3, 8, 5, 2, 6 };
System.out.println(findSecondSmallestItem(arr2));
Integer[] arr3 = new Integer[] { 6, 8, 5, 2, 3 };
System.out.println(findSecondSmallestItem(arr3));
Integer[] arr4 = new Integer[] { 3, 3, 3, 3, 3 };
System.out.println(findSecondSmallestItem(arr4));
Integer[] arr5 = new Integer[] { 3, 3, 3, 2, 3 };
System.out.println(findSecondSmallestItem(arr5));
Integer[] arr6 = new Integer[] { 3, 4, 3, 3, 3 };
System.out.println(findSecondSmallestItem(arr6));
Integer[] arrEmpty = new Integer[] {};
System.out.println(findSecondSmallestItem(arrEmpty));
Integer[] arrOne = new Integer[] { 1 };
System.out.println(findSecondSmallestItem(arrOne));
}
}