[Leetcode] 414. Third Maximum Number 解题报告

来源:互联网 发布:vs2017 java 编辑:程序博客网 时间:2024/06/10 08:37

题目

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: 1Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.

思路

可以用自动排序以及去重的set来实现:遍历数组的每个元素,并且将其加入set中,一旦发现set的个数超过3个,则移除掉最小的一个。由于我们保证了set的规模不超过4,所以整个算法的时间复杂度是O(n),空间复杂度是O(1)。

代码

class Solution {public:    int thirdMax(vector<int>& nums) {        set<int> top_3;        for (auto num : nums) {            top_3.insert(num);            if (top_3.size() > 3) {                top_3.erase(top_3.begin());            }        }        return top_3.size() == 3 ? *top_3.begin() : *top_3.rbegin();    }};