-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path414.第三大的数.py
More file actions
69 lines (66 loc) · 1.36 KB
/
414.第三大的数.py
File metadata and controls
69 lines (66 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#
# @lc app=leetcode.cn id=414 lang=python
#
# [414] 第三大的数
#
# https://leetcode-cn.com/problems/third-maximum-number/description/
#
# algorithms
# Easy (32.97%)
# Likes: 74
# Dislikes: 0
# Total Accepted: 13.4K
# Total Submissions: 40.6K
# Testcase Example: '[3,2,1]'
#
# 给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
#
# 示例 1:
#
#
# 输入: [3, 2, 1]
#
# 输出: 1
#
# 解释: 第三大的数是 1.
#
#
# 示例 2:
#
#
# 输入: [1, 2]
#
# 输出: 2
#
# 解释: 第三大的数不存在, 所以返回最大的数 2 .
#
#
# 示例 3:
#
#
# 输入: [2, 2, 3, 1]
#
# 输出: 1
#
# 解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
# 存在两个值为2的数,它们都排第二。
#
#
#
# @lc code=start
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first,second,third=-float('inf'),-float('inf'),-float('inf')
for i in nums:
if i>first:
first,second,third=i,first,second
elif second<i<first:
second,third=i,second
elif third<i<second:
third=i
return third if third!=-float('inf') else first
# @lc code=end