LeetCode - 414. Third Maximum Number-思路详解- C++
2017-01-10 15:44
423 查看
题目
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.
翻译
给定一个数组,返回数组中的第三大数。如果不存在,则返回最大的数。时间复杂度为O(n)思路
保持一个大小为3的集合。遍历数组,然后将元素插入,如果集合大小小于等于3,则继续,如果大于3,则取消set中第一个元素。接着遍历。
分析:
给一个最大为3的插入,删除一个元素的时间复杂度为O(nlogn),在这里即为O(3)。所以时间负责度为O(n)
代码
class Solution { public: int thirdMax(vector<int>& nums) { set<int> s; for (int num : nums) { s.insert(num); if (s.size() > 3) { s.erase(s.begin()); } } return s.size() == 3 ? *s.begin() : *s.rbegin(); } };
相关文章推荐
- LeetCode - 216. Combination Sum III - 思路详解 - C++
- LeetCode - 228. Summary Ranges - 思路详解- C++
- LeetCode - 162. Find Peak Element - 思路详解 - C++
- LeetCode - 189. Rotate Array - 思路详解 - C++
- LeetCode - 121. Best Time to Buy and Sell Stock - 思路详解 - C++
- LeetCode -485. Max Consecutive Ones - 思路详解 - C++
- LeetCode- 238. Product of Array Except Self - 思路详解 -C++
- LeetCode-268. Missing Number-思路详解-C++
- LeetCode-38. Count and Say-思路详解-C++
- LeetCode - 123. Best Time to Buy and Sell Stock III - 思路详解 - C++
- LeetCode- 1. Two Sum - 思路详解-C++
- LeetCode- 167. Two Sum II - Input array is sorted - 思路详解- C++
- LeetCode- 169. Majority Element - 思路详解 -C++
- LeetCode - 152. Maximum Product Subarray - 思路详解 - C++
- LeetCode - 88. Merge Sorted Array - 思路详解 - C++
- LeetCode - 128. Longest Consecutive Sequence - 思路详解- C++
- LeetCode-386. Lexicographical Numbers-思路详解-C++
- LeetCode - 217. Contains Duplicate - 思路详解 - C++
- LeetCode - 401. Binary Watch - 思路详解-C++
- LeetCode - 283. Move Zeroes - 思路详解 - C++