414. Third Maximum Number 第三大元素

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();
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • 观察的周围的环境,周边的人,觉得好无聊啊,而然我个人的性格总是和他们容不到一起去。很不喜欢这样的环境(在有限...
    一访文阅读 676评论 0 6
  • 起因 进入双臣已经一个月时间,也了解了公司大概的情况。随着企业建设需求的不断升级,更为简化员工的工作,避免重复工作...
    胡金龙阅读 1,429评论 0 0
  • 一查账,你就有风险:这三大税务问题须重点关注! 第一:往来问题 1公司出资购买房子车子,权利人却写成股东 实际工作...
    Dflower阅读 95评论 0 0