LeetCode 414. Third Maximum Number
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.
Level: Easy
Solution in Java:
First, we will look for those Array which has three or more distinct elements,
for these arrays, the standard process would be to sort the array first, then remove the duplicates and then return the last third element as the Third Distinct Maximum.
For those arrays, that don’t have three or more distinct elements, we have to return the Greatest element present.
But if we use TreeSet, it can handle sorting and removing duplicates by itself. So after using TreeSet, we have to get the last third element if the size of the TreeSet is greater than or equal to three or the last element if the size is below three, however, we don’t have the get method available in TreeSet, so we will convert this TreeSet into an ArrayList.
Below is our Final Solution for the Given Problem Statement.
class Solution {
public int thirdMax(int[] nums) {
int L = nums.length;
Set<Integer> s = new TreeSet<>();
for(int i:nums){
s.add(i);
}
List<Integer> ss = new ArrayList<Integer>(s);
L = ss.size();
if(L>=3 ){
return ss.get(L-3);
}
return ss.get(L-1);
}
}
Another Approach :
Use Max-Priority-Queue and poll last three elements and return the third one.
Similar Problem: Leetcode 215. Kth Largest Element in an Array
[Level: Medium]
Solution: Java Solution by Rohit Mittal
Happy Coding!!!
Do upvote if you like the Solution.
Any queries or suggestions? Sure!! Ping me :
* LinkedIn
* Twitter
* GitHub
* Medium