414. Third Maximum Number
414.1 题目描述:
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.
414.2 解题思路:
思路一:利用set集合。首先将数组nums转换为set,去除重复元素。(Python中需要再次对set取list,这是因为set不存在index),如果set的大小小于3,则直接返回其中最大的数。依次设置第一大fmax=nums[0]、第二大smax=-65536、第三大tmax=-65536。遍历nums的set集合。如果当前值大于fmax,则依次改变tmax=smax,smax=fmax,fmax=nums[i];否则,如果当前值大于smax,则依次改变tmax=smax,smax=nums[i];否则,如果当前值大于tmax,则改变tmax=nums[i]。遍历结束,返回tmax即可。
思路二:分为C++和Python。分别利用C++和Python中set的性质即可。
C++:在C++中,set是默认从小到大排序的,所以在遍历nums插入set的同时,可以判断其set的大小,当大小超过3时,将其set.begin()
即第一个元素删除,保证每次set中只有3个元素,且是前3个最大的。遍历结束后,如果set的大小等于3,则返回set.begin()第一个值,即第三大的数;否则返回set.rbigin()反向第一个值,即最大的数。Python:在Python中,set是无序的,且不可通过下标访问的。可以使用max()函数。如果set大小小于3,则直接返回max(set),否则,移除两次set中的最大值set.remove(max(set)),然后返回此时set中的最大值即可。
414.3 C++代码:
1、思路一代码(13ms):
class Solution128 {
public:
int thirdMax(vector<int>& nums) {
set<int>num;
for (int i = 0; i < nums.size();i++)
num.insert(nums[i]);
set<int>::iterator it = num.begin();
if (num.size() == 1)
return *it;
if (num.size() == 2)
return *it > *(it++) ? *it : *(it++);
int fmax = *it;
int smax = -65536;
int tmax = -65536;
for (it; it!=num.end(); it++)
{
if (*it>fmax)
{
tmax = smax;
smax = fmax;
fmax = *it;
}
else
{
if (*it>smax)
{
tmax = smax;
smax = *it;
}
else
{
if (*it > fmax)
fmax = *it;
}
}
}
return tmax;
}
};
2、思路二代码(13ms)
class Solution128_1 {
public:
int thirdMax(vector<int>& nums) {
set<int>num;
for (int i = 0; i < nums.size();i++)
{
num.insert(nums[i]);
if (num.size()>3)
num.erase(num.begin());
}
return num.size() == 3 ? *num.begin() : *num.rbegin();
}
};
414.4 Python代码:
1、思路一代码(32ms)
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums=set(nums)
nums=list(nums)
if len(nums)==1:
return nums[0]
if len(nums)==2:
return max(nums[0],nums[1])
fmax=nums[0]
smax=-65536
tmax=-65536
for i in range(len(nums)):
if nums[i]>fmax:
tmax=smax
smax=fmax
fmax=nums[i]
else:
if nums[i]>smax:
tmax=smax
smax=nums[i]
else:
if nums[i]>tmax:
tmax=nums[i]
return tmax
2、思路二代码(42ms)
class Solution1(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums=set(nums)
if len(nums)<3:
return max(nums)
nums.remove(max(nums))
nums.remove(max(nums))
return max(nums)