414. Third Maximum Number

c++ STL

set容器

insert后的set是从小到大排序的。

set.begin() < .. < set.rbegin()

参考代码:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int> MaxSet;
        for(int i=0; i<nums.size(); i++){
            MaxSet.insert(nums[i]);
            if(MaxSet.size()>3) MaxSet.erase(MaxSet.begin());
        }
        if(MaxSet.size()==3) return *MaxSet.begin();
        else return *MaxSet.rbegin();
    }
};

相关推荐