从数组中获取最大的两个值

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_25605637/article/details/79413875

思路:考虑到最大值有可能在第一位,不能把最大值和次大值都赋值为数组的第一个数

代码:

public class Test {

    public static void main(String[] args) {
        int[] a = {9, 3, 9, 4, 3, 3};
        int[] b = {9, 8, 7, 6, 5};
        int[] c = {9, 9, 11, 8, 12};
        //9 9
        cal(a);
        //9 8
        cal(b);
        //12 11
        cal(c);
    }

    public static void cal(int[] array) {
        int max1, max2;
        if (array[0] > array[1]) {
            max1 = array[0];
            max2 = array[1];
        } else {
            max1 = array[1];
            max2 = array[0];
        }
        for (int i = 2; i < array.length; i++) {
            if (array[i] > max1) {
                max2 = max1;
                max1 = array[i];
            } else if (array[i] > max2){
                max2 = array[i];
            }
        }
        System.out.println(max1 + " " + max2);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_25605637/article/details/79413875