Skip to content

Commit 671973c

Browse files
author
weiy
committed
third maximum numbers
1 parent 0c99342 commit 671973c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Diff for: Array/ThirdMaximumNumbers.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
3+
4+
Example 1:
5+
Input: [3, 2, 1]
6+
7+
Output: 1
8+
9+
Explanation: The third maximum is 1.
10+
Example 2:
11+
Input: [1, 2]
12+
13+
Output: 2
14+
15+
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
16+
Example 3:
17+
Input: [2, 2, 3, 1]
18+
19+
Output: 1
20+
21+
Explanation: Note that the third maximum here means the third maximum distinct number.
22+
Both numbers with value 2 are both considered as second maximum.
23+
24+
返回第三大的数,如果不存在则返回最大的,重复的算一个。
25+
https://leetcode.com/problems/third-maximum-number/description/
26+
27+
找到第 k 大个数一般的思路有:
28+
1. 排序后放到数组中,排序算法使用归并和快排在理想情况下都是O(nlogn),归并比较稳定一些。之后的索引是O(1)。
29+
这种的适合并不需要插入的情况,因为每次插入的时间复杂度为 O(n)。
30+
31+
2. 建立二叉搜索树,进阶的话红黑树或AVL树。
32+
这种情况下搜索和插入在理想情况下都是O(logn)。
33+
34+
3. 就此题来说的O(n)思路:
35+
建立三个变量,first,second,third,首先确保不是None,然后挨个放数据,最后输出结果。
36+
37+
这里直接用排序了。
38+
39+
40+
"""
41+
class Solution(object):
42+
def thirdMax(self, nums):
43+
"""
44+
:type nums: List[int]
45+
:rtype: int
46+
"""
47+
nums = set(nums)
48+
if len(nums) < 3:
49+
return max(nums)
50+
51+
return sorted(nums, reverse=True)[2]

0 commit comments

Comments
 (0)