Easy
430810FavoriteShare
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.
C++:
/*
* @Autor: SourDumplings
* @Date: 2019-09-24 15:17:43
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/third-maximum-number/
*/
#include <climits>
class Solution
{
public:
int thirdMax(vector<int> &nums)
{
int f = INT_MIN, s = INT_MIN, t = INT_MIN;
for (auto &&i : nums)
{
if (i > f)
{
f = i;
}
}
for (auto &&i : nums)
{
if (i > s && i < f)
{
s = i;
}
}
bool hasT = false;
for (auto &&i : nums)
{
if (i >= t && i < s)
{
hasT = true;
t = i;
}
}
return hasT ? t : f;
}
};
Java:
/*
* @Autor: SourDumplings
* @Date: 2019-09-24 15:31:53
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/third-maximum-number/
*/
class Solution
{
public int thirdMax(int[] nums)
{
int f = Integer.MIN_VALUE;
int s = Integer.MIN_VALUE;
int t = Integer.MIN_VALUE;
for (int i : nums)
{
if (i > f)
{
f = i;
}
}
for (int i : nums)
{
if (i > s && i < f)
{
s = i;
}
}
boolean hasT = false;
for (int i : nums)
{
if (i >= t && i < s)
{
hasT = true;
t = i;
}
}
return hasT ? t : f;
}
}