The Third Maximum Number problem involves finding the third distinct maximum number in an array. If the third maximum does not exist, return the maximum number.
This problem can be solved using a set or a min-heap to track distinct maximum numbers.
class Solution {
public int thirdMax(int[] nums) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.contains(num)) {
seen.add(num);
minHeap.offer(num);
if (minHeap.size() > 3) {
minHeap.poll(); // Remove the smallest element
}
}
}
// If there are less than 3 distinct numbers, return the maximum
if (minHeap.size() < 3) {
while (minHeap.size() > 1) {
minHeap.poll();
}
}
return minHeap.peek();
}
}
O(N log 3)
โ Adding and removing elements from the heap.O(N log 3)
.Input: nums = [3, 2, 1]
Output: 1
Explanation:
- The distinct maximum numbers are [3, 2, 1].
- The third maximum number is 1.