[LeetCode] Third Maximum Number

414. Third Maximum Number

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int thirdMax(vector<int>& nums) {
long long ma1 = LLONG_MIN, ma2 = LLONG_MIN, ma3 = LLONG_MIN;
for(auto& x : nums) {
if(x <= ma3) continue;
if(ma1 < x) {
ma3 = ma2;
ma2 = ma1;
ma1 = x;
} else if(ma1 > x) {
if(ma2 < x) {
ma3 = ma2;
ma2 = x;
} else if(ma2 > x) {
if(ma3 < x) ma3 = x;
}
}
}
return ma3 == LLONG_MIN ? ma1 : ma3;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/02/09/PS/LeetCode/third-maximum-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.