Finding max and min in arrays Find the second largest element in an array

Implement a method to find the second largest number in an array of ints.

If the input array is empty or contains only a single number, the method must return Integer.MIN_VALUE.

If the input array contains multiple largest elements, consider them as the same value.

Sample Input 1:

1 5 3 1 2 4 6

Sample Output 1:

5

Sample Input 2:

17 17 -10 -10 -15

Sample Output 2:

-10

Sample Input 3:

15 15

Sample Output 3:

-2147483648
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static int findSecondLargestNumber(int[] numbers) {
        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;
        
        for (int i : numbers) {
            if (i > largest) {
                secondLargest = largest;
                largest = i;
            } else if (i > secondLargest && i != largest) {
                secondLargest = i;
            }
        }
        
        return secondLargest;
    }

    /* Do not change code below */
    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final int[] numbers;
        if (scanner.hasNextInt()) {
            numbers = Arrays.stream(scanner.nextLine().split("\\s+"))
                    .mapToInt(Integer::parseInt)
                    .toArray();
        } else {
            numbers = new int[0];
        }
        System.out.println(findSecondLargestNumber(numbers));
    }
}

posted @ 2020-08-16 11:36  longlong6296  阅读(125)  评论(0)    收藏  举报