思路:如果当前元素大于最大数 a1,则让第二大数a2等于原来的最大数 a1,再把当前元素的值赋给 a1
package com.ht.timelycloud.algorithm; /** * @ClassName: SecondBigNumber * @Description: 快速获取一个整数数组中 第二大的整数 * @author Timely-03 * @date 2020年5月13日 * */ public class SecondBigNumber { public static void main(String[] args) { int a1 = 0; // 第一大的数 int a2 = 0; // 第二大的数 int[] arr = new int[] {999,999,4,5,6,7,3,2,169,90,100,4,5,22,3,33,12,102,170,140,11,23}; for (int i=0,len=arr.length; i<len; i++) { // 第一大的数 & 第二大的数 if (arr[i] > a1) { a2 = a1; a1 = arr[i]; continue; } // 第二大的数 // arr[i] != a1 过滤最大数重复的情况(按照场景决定是否需要过滤) if (arr[i] > a2 && arr[i] != a1) { a2 = arr[i]; } } System.out.println(a1); System.out.println(a2); } }