码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-08-18 13:58:14      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:put   single   ext   multi   array   stream   value   change   class   

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));
    }
}

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

标签:put   single   ext   multi   array   stream   value   change   class   

原文地址:https://www.cnblogs.com/longlong6296/p/13511956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!