// 1.从数组中找出第三大的数,例如{10,10,9,9,8,8,7,7} 第三大的数是8
public class ThirdLargestNumber {
public static void main(String[] args) {
int[] nums = {10, 10, 9, 9, 8, 8, 7, 7};
int thirdLargest = findThirdLargest(nums);
System.out.println("第三大的数是:" + thirdLargest);
}
public static int findThirdLargest(int[] nums) {
if (nums.length < 3) {
throw new IllegalArgumentException("数组长度不足");
}
Integer firstMax = null;
Integer secondMax = null;
Integer thirdMax = null;
for (Integer num : nums) {
if (num.equals(firstMax) || num.equals(secondMax) || num.equals(thirdMax)) {
continue;
}
if (firstMax == null || num > firstMax) {
thirdMax = secondMax;
secondMax = firstMax;
firstMax = num;
} else if (secondMax == null || num > secondMax) {
thirdMax = secondMax;
secondMax = num;
} else if (thirdMax == null || num > thirdMax) {
thirdMax = num;
}
}
if (thirdMax == null) {
throw new IllegalArgumentException("不存在第三大的数");
}
return thirdMax;
}
}
标签:secondMax,firstMax,nums,第三,num,数组,thirdMax,null
From: https://www.cnblogs.com/chenyi502/p/17694638.html