给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)
Example 1:
Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Example 2:
Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.
1:注意例子中标红的地方,当第三个最大的数不存在时,输出第一个最大的数。此外,这三个最大的数彼此之间不能重复(效率较低:36s)
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
com = [float("-inf")] * 3 #代替存储三个最大的数
for i in range(len(nums)): #时间复杂度O(n)
for j in range(-1, -4, -1): #倒序访问con列表
if nums[i] > com[j]: #按规则循环替换三个最大的数
com[j], nums[i] = nums[i], com[j]
elif nums[i] == com[j]: #如果当前数和三个最大的数之一重复,就结束内层for循环
break
return com[2] if com[0] == float("-inf") else com[0]
参考他人:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max1 = max2 = max3 = None
for num in nums:
if num >max1:
max2,max3 = max1,max2
max1 = num
elif num < max1 and num >max2:
max3,max2 = max2,num
elif num > max3 and num < max2:
max3= num
return max1 if max3 is None else max3
2:利用set()去除列表中重复数字,再转列表为nums,接着用nums.sort()方法对列表排序(参考他人,但该方法无法保证满足时间复杂O(n)的条件)
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = list(set(nums))
nums.sort()
if len(nums)<3:
return nums[-1]
else:
return nums[-3]
参考他人:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = { }
for num in nums:
if num in dic:
dic[num] += 1
else:
dic[num] = 1
d = sorted(dic.keys())
if len(d) >= 3:
return d[-3]
else:
return max(d)
算法题来自:https://leetcode-cn.com/problems/third-maximum-number/description/