LetCode 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.
第一种方法是用set先去重,然后再排序,最后根据条件返回对应的值
def thirdMax(nums: List[int]) -> int:
count = 0
ans = list(set(nums))
ans.sort(reverse=True)
if len(ans) >= 3:
return ans[2]
else:
return ans[0]
第二种方法是引入中间变量来比较大小
def thirdMax(nums: List[int]) -> int:
max1, max2, max3 = float('-inf'), float('-inf'), float('-inf')
for num in nums:
if num > max1:
max1, max2, max3 = num, max1, max2
if num > max2 and num != max1:
max2, max3 = num, max2
if num > max3 and num != max2 and num != max1:
max3 = num
if max3 != float('-inf'):
return max3
else:
return max1

浙公网安备 33010602011771号