Difficulty: Easy
Topics: Array, Sorting
Platform: Leetcode
Problem Statement
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 Statement Simplified
Give back the 3rd largest number from the array if it exists, else give back the largest number.
Mistakes and Learning
Confusing over the array indexing and length—array indexing starts at 0 and length starts at 1, always forget that.
Example 1
Input: nums = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
Example 2
Input: nums = [1,2]
Output: 2
Explanation:
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.
Key Insight
- Sort the array.
- Get the unique array.
- If less than 3, then return the largest.
- Else return the nums.length - 3.
Algorithm
- Sort the array.
- Initialize an array to store the unique array, using stream , distinct operation and toArray to make it into an array.
- If the array length is less than 3 then return the last digit of the array.
- Else return the element in total length-3.
- End if.
Algorithm in simple words
Fisrt sort the array in ascending order to get the elements in order. Then find out the duplicating element using distinct() operation and discard it.
Then using an if statment check if the array length is less than 3 , if yes then return the last digit which will be the largest digit.
If greater than 3 then return the element in total length-3 that will be the 3rd largest digit.
Java code
class Solution {
public int thirdMax(int[] nums) {
Arrays.sort(nums);
int[] uniqueArr= Arrays.stream(nums).distinct().toArray();
if(uniqueArr.length<3){
return uniqueArr[uniqueArr.length-1];
}
else{
return uniqueArr[uniqueArr.length-3];
}
}
}
Time & Space Complexity
Time Complexity: O(nlogn)
Space Complexity: O(n)
Top comments (0)