zoukankan      html  css  js  c++  java
  • 求数组中第二大数

    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;
    
        }
    
    }
  • 相关阅读:
    js 对象克隆的三种方式
    css超出行数隐藏
    express 中的登录-注册
    Git 常用命令
    mongodb 基本操作
    【服务器】阿里云
    【mongoDb进阶】mongoDb中的聚合管道
    express中操作数据库--Mongoose
    vuex常见问题
    ADC采样时间
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4619130.html
Copyright © 2011-2022 走看看