#414
Easy Algorithms Third maximum number
Array Sorting
38.9% acceptance
Jan 13, 2026
3509
3507
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn third_max(nums: Vec<i32>) -> i32 {
let mut first = None;
let mut second = None;
let mut third = None;
for &num in &nums {
if first == Some(num) || second == Some(num) || third == Some(num) {
continue;
}
if first.is_none() || num > first.unwrap() {
third = second;
second = first;
first = Some(num);
} else if second.is_none() || num > second.unwrap() {
third = second;
second = Some(num);
} else if third.is_none() || num > third.unwrap() {
third = Some(num);
}
}
third.unwrap_or(first.unwrap())
}
}