Third Maximum Number

2017/12/2 posted in  leetcode

利用set的自动排序和去除重复元素来解决问题。

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