Third Maximum Distinct Number in List
Given a non-empty list of integers nums, return its third largest distinct value. If fewer than three distinct values exist, return the largest value.
Duplicate occurrences of a value are counted only once when determining the maximum values.
Method Signature
int thirdMax(List<Integer> nums)
nums contains the integers to examine.
- Return the third largest distinct integer when at least three distinct integers exist.
- Otherwise, return the largest integer in
nums.
Constraints
1 ≤ nums.size() ≤ 10,000
-2,147,483,648 ≤ nums.get(i) ≤ 2,147,483,647
- The solution must run in
O(n) time.
Examples
Example 1
Method call: thirdMax(nums = List.of(8, 3, 12, 5))
Output: 5
Explanation: The distinct values in descending order are 12, 8, 5, 3, so the third maximum is 5.
Example 2
Method call: thirdMax(nums = List.of(7, 7, 4))
Output: 7
Explanation: Only two distinct values exist, so the maximum value 7 is returned.
Example 3
Method call: thirdMax(nums = List.of(9, 2, 9, 6, 6, 1))
Output: 2
Explanation: After ignoring duplicates, the values in descending order are 9, 6, 2, 1. Therefore, the third maximum is 2.