美文网首页
获取数组中第二大的数字

获取数组中第二大的数字

作者: lanmoyingsheng | 来源:发表于2019-02-13 21:47 被阅读1次
    public class SecMax {
    
        public static void main(String[] args) throws Exception {
    
            int[] arr = {44, 8, 1, 2, 100, 99};
    
            int sec_max = sec_max(arr);
    
            System.out.println(sec_max);
        }
    
    
        static int sec_max(int[] arr) throws Exception {
    
            int length = arr.length;
    
            if (length < 2) {
                throw new Exception("数组不符合条件!");
            }
    
            if (length == 2) {
                return (arr[0] > arr[1] ? arr[1] : arr[0]);
            }
    
            int max = arr[0];
            int sec_max = arr[0];
    
            for (int i = 0; i < length; i++) { 
                
                // sec_max max 
                // 将arr[i]摆到 sec_ma,max 的前、中、后的位置
    
                if (arr[i] > max) {
    
                    sec_max = max;
                    max = arr[i];
    
                } else if (arr[i] > sec_max ) {
                    sec_max = arr[i];
                }
            }
    
    
            return sec_max;
        }
    }
    

    相关文章

      网友评论

          本文标题:获取数组中第二大的数字

          本文链接:https://www.haomeiwen.com/subject/sbejeqtx.html