【LeetCode 力扣 414】第三大的数 ,给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。

学习目标:

目标:熟练运用 Java所学知识


题目内容:

本文内容: 使用Java实现:第三大的数


题目描述

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。

示例 1:

输入:[3, 2, 1]
输出:1
解释:第三大的数是 1

示例 2:

输入:[1, 2]
输出:2
解释:第三大的数不存在, 所以返回最大的数 2 。

示例 3:

输入:[2, 2, 3, 1]
输出:1
解释:注意,要求返回第三大的数,是指第三大且唯一出现的数。 存在两个值为2的数,它们都排第二。

解题思路

首先定义三个变量first,second,third,分别表示第一大的数、第二大的数、第三大的数,

然后遍历数组元素,分为一下几种情况

  • 如果元素大于first,进行以下赋值
third = second;
second = first;
first = i;
  • 如果元素大于second,进行以下赋值
third = second;
second = i;
  • 如果元素大于third,进行以下赋值
third = i;
  • 如果元素等于first,或者等于second,或者小于等于third,则进行下次循环

实现代码

public class Practice_02 {
    
    
    public static void main(String[] args) {
    
    
        int[] nums = {
    
    1,2,3,4,5};
        System.out.println(thirdMax(nums));
    }
    public static int thirdMax(int[] nums) {
    
    
        long first = Long.MIN_VALUE;
        long second = Long.MIN_VALUE;
        long third = Long.MIN_VALUE;
        for (int i : nums) {
    
    
            if (third >= i || second == i || first == i) {
    
    
                continue;
            } else if (i > first) {
    
    
                third = second;
                second = first;
                first = i;
            } else if (i > second) {
    
    
                third = second;
                second = i;
            } else {
    
    
                third = i;
            }
        }
        return third == Long.MIN_VALUE ? (int) first : (int) third;
    }


}

运行结果

3

猜你喜欢

转载自blog.csdn.net/zhangxxin/article/details/113120783