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. Your solution must be O(n).
For example:
nums = [3,2,1]
should return 1
because the first distinct maximum is 3, the second is 2, and the third is 1.nums = [1,2]
should return 2
because the first distinct maximum is 2, the second is 1, and the third does not exist, thus return the max which is 2.nums = [2,2,3,1]
should return 1
because the first distinct maximum is 3, the second distinct maximum is 2 (both 2's are counted together since they have the same value), and the third distinct maximum is 1.What is the most efficient way to solve this and what is the Big O runtime?
Given an integer array nums
, the task is to find the third distinct maximum number in the array. If the third maximum does not exist, return the maximum number.
A straightforward approach would be to sort the array in descending order and then find the third distinct element. This involves sorting and then iterating through the sorted array to find distinct elements.
def third_max_naive(nums):
nums = sorted(list(set(nums)), reverse=True)
if len(nums) >= 3:
return nums[2]
elif len(nums) > 0:
return nums[0]
else:
return None # or handle the empty list case as appropriate
set()
and converting back to list takes O(n) time.A more efficient approach involves iterating through the array once and keeping track of the first, second, and third maximum numbers.
max1
, max2
, and max3
to negative infinity (or None in Python).max1
, update max3 = max2
, max2 = max1
, and max1 = num
.max2
and not equal to max1
, update max3 = max2
and max2 = num
.max3
and not equal to max1
and max2
, update max3 = num
.max3
is still negative infinity (or None), return max1
. Otherwise, return max3
.import math
def third_max_optimal(nums):
max1 = float('-inf')
max2 = float('-inf')
max3 = float('-inf')
for num in nums:
if num > max1:
max3 = max2
max2 = max1
max1 = num
elif num > max2 and num != max1:
max3 = max2
max2 = num
elif num > max3 and num != max1 and num != max2:
max3 = num
if max3 == float('-inf'):
return max1
else:
return max3
1 <= nums.length <= 10^4
, so we do not need to consider an empty array.max1
, max2
, and max3
to negative infinity.The optimal solution provides a more efficient way to find the third distinct maximum number in an array with O(n) time complexity and O(1) space complexity, making it preferable over the naive O(n log n) solution.