求数组中第三大的数

// 1.从数组中找出第三大的数,例如{10,10,9,9,8,8,7,7} 第三大的数是8
414. 第三大的数

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

作者:静默虚空
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

posted @   Chenyi_li  阅读(185)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示