第三大的数

🎯 问题描述(来源于LeetCode)

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。

💻 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def thirdMax(self, nums: List[int]) -> int:
max2=max(nums)
max1=max(nums)
if len(nums)<3:
return max1
pid=0
while 1 :
nums.remove(max1)
if pid ==2 or len(nums)==0:
break
if max1!=max(nums):
pid+=1
max1=max(nums)
if pid<2:
return max2
else:
return max1

📊 性能分析

提交结果

  • 运行时间:0ms击败100.00%
  • 内存消耗:18.05MB击败84.97%

复杂度验证

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)