0414. Third Maximum Number

0414. Third Maximum Number #

题目 #

  • 给定一个非空数组,返回该数组中 第三大的数
  • 如果不存在,则返回数组中最大的数。
  • 注: 要求返回第三大的数,是指在所有不同数字中排第三大的数。

思路 #

模拟 + 哈希 #

代码 #

模拟 + 哈希 #

class Solution {
    public int thirdMax(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE, third = Integer.MIN_VALUE;
        for (int num: nums) {
            if (set.contains(num) == false) {
                if (set.size() == 0) first = num;
                else if (set.size() == 1) {
                    second = first > num ? num : first;
                    first = first > num ? first : num;
                }
                else if (set.size() == 2) {
                    if (num > first) { third = second; second = first; first = num; }
                    else if (num > second) { third = second; second = num; }
                    else third = num;
                }
                else {
                    if (num > first) { third = second; second = first; first = num; }
                    else if (num > second) { third = second; second = num; }
                    else if (num > third) { third = num; }
                }
                set.add(num);
            }
        }
        return set.size() > 2 ? third : first;
    }
}

模拟 #

class Solution {
    public int thirdMax(int[] nums) {
        long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE;
        for (int num: nums) {
            if (num > first) { third = second; second = first; first = num; }
            else if (first > num && num > second) { third = second; second = num; }
            else if (second > num && num > third) third = num;
        }
        return third == Long.MIN_VALUE ? (int)first : (int)third;
    }
}