### Find the second smallest integer in array

Problem statement Given an array of integers, find the second smallest integer in that array. Solution

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 |
public class SecondSmallestInteger { public static int solve(int[] arr) { int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; ; for (int i = 0; i < arr.length; i++) { if (arr[i] < smallest) { secondSmallest = smallest; smallest = arr[i]; } else if (arr[i] == smallest) { secondSmallest = smallest; } else if (arr[i] < secondSmallest) { secondSmallest = arr[i]; } } return secondSmallest; } public static void main(String[] args) { int[] arr = { 1, 2, -7, 10, 100, 999, 2, 0, 34, 42 }; int ans = solve(arr); Arrays.sort(arr); if (ans == arr[1]) { System.out.println(ans); } else { System.out.println("Problem"); } } } |