LeetCode 414. Third Maximum Number

来源:互联网 发布:淘宝店铺推广平台 编辑:程序博客网 时间:2024/05/22 05:24

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: 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.

题目大意:

给定一个数组,求出数组中第三大的元素。
1:全部放到set中,直接返回倒数第三个数字即可。
2:把元素一个一个往set中插入,直到所有元素插入完成,如果插入元素后长度超过3,那么“擦除”set中第一个元素,这样可以使中保持set中有三个元素。最后输出set中第一个元素也就是“第三大”元素。
需要注意的是,如果set中元素小于3,那么要输出最大的元素。


题目代码:

class Solution {public:    int thirdMax(vector<int>& nums) {        set<int>s(nums.begin(), nums.end());        set<int>::iterator iter;        iter = s.end();        iter--;        iter--;        iter--;        if(s.size() >= 3)            return *iter;         else            return *s.rbegin();    }};


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();    }};