Description
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.
Discuss
因为有去重的要求, 倘若有重复的直接拼接在后面, 最坏情况下, max1重复很多次, 那要动态开辟一个很大的数组, 在insert时候也无法避免多次比较, 故采用set.
- C++ set
c++ set是自动排序的!! insert之后 ==> 去重+默认从小到大排序
int thirdMax(vector<int>& nums) {
set<int> top3;
for (int num : nums) {
top3.insert(num);
if (top3.size() > 3)
top3.erase(top3.begin());
}
return top3.size() == 3 ? *top3.begin() : *top3.rbegin();
}
- Python set
直观的方式
def thirdMax(self, nums):
nums = set(nums)
if len(nums) < 3:
return max(nums)
nums.remove(max(nums))
nums.remove(max(nums))
return max(nums)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。