This is a easy question. It can Easily done by sorting them and return third element from last.I also use the same logic. But due to duplicate Numbers Firtly remove all duplicate numbers then do the same logic. if nums size less than three after removing duplicates simply return maximum value.
This is my CPP solution.
class Solution {
public:
int thirdMax(vector<int>& nums) {
int j = 0,n=nums.size();
if(n==0){
return 1/0;
}
sort(nums.begin(),nums.end());
for (int i=0; i < n-1; i++){
if (nums[i] != nums[i+1]){
nums[j++] = nums[i];
}
}
nums[j++] = nums[n-1];
if(j<3){
return nums[j-1];
}
return nums[j-3];
}
};
Time Complexity O(nlog(n)); Space Complexity O(1);