414. Third Maximum Number

Input: nums = [3,2,1]
Output: 1
Explanation: The third maximum is 1.
Input: nums = [1,2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Input: nums = [2,2,3,1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
class Solution {
public:
int thirdMax(vector<int>& nums) {

sort(nums.begin(), nums.end(), greater<int>());
if(nums.size() < 3){
return nums[0];
}
int m1 = nums[0];
int m2 = nums[1];
int m3 = nums[2];
for(int i=1; i<nums.size(); i++){
if(nums[i] == m1){
if(i+1 < nums.size()){
m2 = nums[i+1];
}
}
if(nums[i] == m2){
if(i+1 < nums.size()){
m3 = nums[i+1];
}

}

if(m1>m2 && m2>m3){
return m3;
}
}

return m1;
}
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store