# LeetCode.414.Third Maximum Number 数组中第三大的数

## 题目描述

414 Third Maximum Number
https://leetcode-cn.com/problems/third-maximum-number/

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

## 解题过程

private static class SolutionV2020 {
public int thirdMax(int[] nums) {
Integer max = null, secondMax = null, thirdMax = null;
for (int n : nums) {
if (null == max || n > max) {
thirdMax = secondMax;
secondMax = max;
max = n;
} else if (n < max && (null == secondMax || n > secondMax)) {
thirdMax = secondMax;
secondMax = n;
} else if ((secondMax != null && n < secondMax) && (thirdMax == null || n > thirdMax)) {
thirdMax = n;
}
}
return thirdMax != null ? thirdMax : max;
}
}

## GitHub代码

algorithms/leetcode/leetcode/_414_ThirdMaximumNumber.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_414_ThirdMaximumNumber.java

288

#### 页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent: