# Four lines. Neat and clear C++ code run in O(n) time with STL set.

• It is easy to solve this problem using STL set in C++.
The code:

int thirdMax(vector<int>& nums) {
set<int> newNums = set<int>(nums.begin(), nums.end());
set<int>::iterator it = newNums.end();
if (newNums.size() < 3) return *(--it);
else return *(--(--(--it)));
}

• That's not O(n).

• @ManuelP Could please tell me why. Thanks forward!

• What made you think it's O(n)?

• @ManuelP Thanks for your correction! I am a new learner and I misunderstand the time complexity. So sorry.

• @geeook
If you want to use set<int>, it can be written as follows (O(n) time):

int thirdMax(vector<int>& nums) {
set<int, greater<int>> newNums;
for(int num:nums){
newNums.insert(num);
if(newNums.size()>3)newNums.erase(prev(newNums.end()));
}
return (newNums.size()<3)?*newNums.begin() : *newNums.rbegin();
}

• @Hao-Cai Why greater<int>?

• @ManuelP
You may not use it and erase newNums.begin() each time instead;

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.