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.
Example:
Input: nums = [3, 2, 1]
Output: 1
Explanation: The third distinct maximum is 1.
Input: nums = [1, 2]
Output: 2
Explanation: The third distinct maximum does not exist, so the maximum (2) is returned instead.
Input: nums = [2, 2, 3, 1]
Output: 1
Explanation: Note that the third distinct maximum here is 1 because the numbers 2 are considered repeats.
import java.util.*;
public class ThirdMaximumNumber {
public int thirdMax(int[] nums) {
Set<Integer> distinctNumbers = new HashSet<>();
for (int num : nums) {
distinctNumbers.add(num);
}
// If there are less than 3 distinct numbers, return the maximum.
if (distinctNumbers.size() < 3) {
return Collections.max(distinctNumbers);
}
// Convert set to list and sort in descending order.
List<Integer> sortedDistinctNumbers = new ArrayList<>(distinctNumbers);
Collections.sort(sortedDistinctNumbers, Collections.reverseOrder());
// Return the third maximum number.
return sortedDistinctNumbers.get(2);
}
public static void main(String[] args) {
ThirdMaximumNumber solution = new ThirdMaximumNumber();
// Test Case 1
int[] nums1 = {3, 2, 1};
System.out.println(solution.thirdMax(nums1)); // Output: 1
// Test Case 2
int[] nums2 = {1, 2};
System.out.println(solution.thirdMax(nums2)); // Output: 2
// Test Case 3
int[] nums3 = {2, 2, 3, 1};
System.out.println(solution.thirdMax(nums3)); // Output: 1
}
}
This solution ensures that we find the third maximum number in an efficient manner by leveraging a set for uniqueness and sorting to easily retrieve the highest values.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?