💭
LeetCode #414 Third Maximum Number
問題概要
入力値:nums
出力値:num
return the third distinct maximum number in this array
If the third maximum does not exist, return the maximum number
問題のリンク
入力例
nums: [1,2,3]
answer: 1
nums: [1,1,2]
answer: 2
解答例1
計算量:O(n)
Python
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
uniq_nums = list(set(nums))
uniq_nums.sort()
if len(uniq_nums) < 3:
return uniq_nums[-1]
else:
return uniq_nums[-3]
Runtime: 31ms
Beats: 69.85%
C++
public:
int thirdMax(vector<int>& nums) {
set<int> numSet(nums.begin(), nums.end());
auto it = numSet.rbegin();
if (numSet.size() >= 3) {
advance(it, 2);
}
return *it;
}
};
Runtime: 12ms
Beats: 12.22%
Discussion