求数组中第二大数

public class SecondMax {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a[]={11,4,5,6,6,1,2,7,8,3};
        int res=findSecond(a);
        System.out.println(res);
        
    }
    public static int  findSecond(int[] array){
        if(array==null||array.length<2)
            return -1;
        /*int first=0;
        int second=1;
        for(int i=2;i<array.length;i++){
            if(array[i]>array[first]||array[i]>array[second]){
                int temp=Math.min(array[first], array[second]);
                if(array[first]==temp)//注意此处的处理,如果array[i]大于其中任何一个,需要将array[i]和最小的交换
                    first=i;
                else{
                    second=i;
                }
                if(array[first]>array[second]){
                    second=i;
                }else
                    first=i;

            }
            return Math.min(array[first], array[second]);

        }*/
        int smaller=Math.min(array[0], array[1]);
        int  bigger=Math.max(array[0], array[1]);//不需要标注下标
        for(int i=2;i<array.length;i++){
            if(array[i]>bigger){
                smaller=bigger;
                bigger=array[i];
            }else if(array[i]>smaller){
                smaller=array[i];
            }
        }
        return smaller;

    }

}
原文地址:https://www.cnblogs.com/qiaomu/p/4619130.html