一个数组求倒数第二个大值

2019-1-5

片段 1片段 2


TreeSet实现

public static void main(String[] args) {

        int[] ints = {9, 4, 7, 9, 4, 11, 3};
        Listbing listbing = new Listbing();
        System.out.println(listbing.getSecondNum(ints));
    }

    private int getSecondNum(int[] ints) {

        TreeSet<Integer> set = new TreeSet<>();
        for (int insNUm : ints) {
            set.add(insNUm);
        }

        set.remove(set.last());
        System.out.println(set);

        return set.pollLast();

    }


循环实现

 public static void main(String[] args) {

        int[] ints = {9, 4, 7, 9, 4, 11, 3};
        Listbing listbing = new Listbing();
        System.out.println(listbing.getSecondNum(ints));
    }

    private int getSecondNum(int[] sourceData){
        if(sourceData==null || sourceData.length==0){
            return -1;
        }
        int max=Integer.MIN_VALUE;
        int secondMax=Integer.MIN_VALUE;
        for(int i=0;i<sourceData.length;i++){
            if(sourceData[i]>max){
                secondMax=max;
                max=sourceData[i];
            }else{
                if(sourceData[i]>secondMax){
                    secondMax=sourceData[i];
                }
            }
        }
        return secondMax;
    }

下载地址

百度网盘
密码: