美文网首页
414. Third Maximum Number 第三大元素

414. Third Maximum Number 第三大元素

作者: 这就是一个随意的名字 | 来源:发表于2017-07-30 10:02 被阅读0次

    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.

    给定一非空整数数组,返回其第三小的元素,若不存在则返回最大的数。算法时间控制在O(n)。这里重复的数字视为一个。


    思路
    一般选择问题,选第三大。
    直接进行扫描,记录第三大或最大的做法存在如下错误:当若使用int型变量记录元素,当第三大恰好为INT_MIN时将出现错误,因为无法判定这里的INT_MIN是扫描出的第三大还是没找到第三大而留下的变量初值。
    正确的做法是使用set,利用set元素排列有序的特性。

    class Solution {
    public:
        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();
        }
    };
    

    相关文章

      网友评论

          本文标题:414. Third Maximum Number 第三大元素

          本文链接:https://www.haomeiwen.com/subject/spuhlxtx.html