求数组中第三大的数

发布时间 2023-09-11 21:55:26作者: Chenyi_li

// 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;
    }
}