// class Solution {
// public:
// int thirdMax(vector<int>& nums) {
// //The elements of set couldn't be changed. And couldn't be found by index.
// set<int> temp;
// for(int i:nums)
// temp.insert(i);
// if(temp.size()>=3){
// set<int>::iterator p = temp.end();
// p--;
// p--;
// p--;
// return *p;
// }
// else
// return *(--temp.end());
// return 0;
// //return temp.size()>3?*(temp.begin()+3):*(temp.end()-1);
// }
// };
class Solution{
public:
int thirdMax(vector<int>& nums){
set<int> temp;
for(int i : nums){
temp.insert(i);
if(temp.size()>3)
temp.erase(temp.begin());
}
return temp.size()==3?*temp.begin():*temp.rbegin();
}
};
erase函数是顺序容器和关联容器都有的;
两种容器都可以调用.begin(),.end(),.rbegin(0,.rend();
关联容器的迭代器是双向迭代器,只能使用p++, p--。不能是p+i这种;
顺序容器的迭代器是随机迭代器,可以使用p+i这种;
适时使用rbegin()避免了麻烦