class Solution {
public:
void siftdown(vector<int>& nums, int e, int begin, int end){
int i = begin;
int j = 2*begin + 1;
while(j<end){
if(j+1 < end && nums[j+1] > nums[j]){
j++;
}
if(e > nums[j]){
break;
}
nums[i] = nums[j];
i = j;
j = 2*i + 1;
}
nums[i] = e;
}
int thirdMax(vector<int>& nums) {
if(nums.empty()){
return 0;
}
if(nums.size() <=2){
return *std::max_element(nums.begin(), nums.end());
}
int ma = *std::max_element(nums.begin(), nums.end());
int last=-1000;
int topk = 3;
auto end = (int)nums.size();
for(auto k = end/2; k>=0;k--){
siftdown(nums, nums[k], k, end);
}
auto n = nums;
for(int k = end-1;k>=0;k--){
int e = nums[k];
if(last != nums[0]){
topk--;
last = nums[0];
}
if(topk==0){
return nums[0];
}
siftdown(nums, e, 0, k);
}
return ma;
}
};