# Leetcode Third Maximum Number problem solution

In this Leetcode Third Maximum Number problem solution we have given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.

## Problem solution in Python.

```class Solution:
def thirdMax(self, nums: List[int]) -> int:
d=len(set(nums))
x=sorted(set(nums))
if d==2:
return x[-1]
elif d==1:
return nums[0]
else:
return x[-3]
```

## Problem solution in Java.

```public int thirdMax(int[] nums)
{
int keepMax = nums[0];
int thirdMax = keepMax;

long max = Long.MAX_VALUE;
for (int i = 0; i < 3; i++)
{
long tmp = Long.MIN_VALUE;
for (int j = 0; j < nums.length; j++)
{
if (nums[j] < max && nums[j] > tmp) tmp = nums[j];
}
if (i == 0) { keepMax = (int)tmp; max = tmp; }

if (i == 1) { max = tmp;}

if (i == 2)
{
if (tmp == Long.MIN_VALUE) return keepMax;
else thirdMax = (int)tmp;
}
}

return thirdMax;
}
```

## Problem solution in C++.

```class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int>S(nums.begin(),nums.end());
priority_queue<int> pq(S.begin(),S.end());
if(pq.size() == 1 || pq.size() == 2) return pq.top();
pq.pop();
pq.pop();
return pq.top();
}
};
```

## Problem solution in C.

```int j=0;
int length=0;
int m=0;
int* r= malloc (sizeof(int)*numsSize) ;
for(int i=0;i<numsSize-1;i++)
{
for( j=0;j<numsSize-1-i;j++)
{
if(nums[j]<nums[j+1])
{
int temp = nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
}
}
}

for (int i=0; i<numsSize; i++)
{
for (j=0; j<i; j++)
{
if (nums[i] == nums[j])
break;
}
if (i == j)
{
r[m++]=nums[i];
length++;
}

}

if(length>=3)
return r[2];
else
return r[0];
```