Sponsored
This approach involves first sorting the array and then selecting distinct maximums from the sorted array. We can use a set to easily manage distinct elements. After constructing a set, we check if the size of the set is at least 3; if so, we find the third largest by accessing the sorted array of distinct elements, otherwise, return the maximum element.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(1) as sorting is done in place with qsort.
1const thirdMax = function(nums) {
2 const distinctNums = [...new Set(nums)].sort((a, b) => b - a);
3 return distinctNums.length < 3 ? distinctNums[0] : distinctNums[2];
4};
5
6console.log(thirdMax([2, 2, 3, 1]));
In JavaScript, the solution uses a Set to filter out duplicates and then sorts the array in descending order. If there are less than 3 distinct numbers, it returns the largest number. Otherwise, it returns the third largest distinct number.
This approach keeps track of the three largest distinct numbers iteratively as it processes the array. It uses variables to track them and updates them as it iterates through each number. This way, it can achieve O(n) time complexity without additional set or sorting overhead.
Time Complexity: O(n) because it performs a single pass over the array.
Space Complexity: O(1) as only constant space is used for tracking the maximums.
1
The Java solution also uses long to differentiate uninitialized state for three distinct maximums and completes insightfully by returning the correct maximum based on the presence of a true third maximum distinct value. First three checks assign new maximum values when their conditions are satisfied.