This repository was archived by the owner on Dec 20, 2021. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ # No.414 第三大的数
2
+ <p >给你一个非空数组,返回此数组中 <strong >第三大的数</strong > 。如果不存在,则返回数组中最大的数。</p >
3
+
4
+ <p >  ; </p >
5
+
6
+ <p ><strong >示例 1:</strong ></p >
7
+
8
+ <pre ><strong >输入:</strong >[3, 2, 1]
9
+ <strong >输出:</strong >1
10
+ <strong >解释:</strong >第三大的数是 1 。</pre >
11
+
12
+ <p ><strong >示例 2:</strong ></p >
13
+
14
+ <pre ><strong >输入:</strong >[1, 2]
15
+ <strong >输出:</strong >2
16
+ <strong >解释:</strong >第三大的数不存在, 所以返回最大的数 2 。
17
+ </pre >
18
+
19
+ <p ><strong >示例 3:</strong ></p >
20
+
21
+ <pre ><strong >输入:</strong >[2, 2, 3, 1]
22
+ <strong >输出:</strong >1
23
+ <strong >解释:</strong >注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
24
+ 此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。</pre >
25
+
26
+ <p >  ; </p >
27
+
28
+ <p ><strong >提示:</strong ></p >
29
+
30
+ <ul >
31
+ <li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
32
+ <li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
33
+ </ul >
34
+
35
+ <p >  ; </p >
36
+
37
+ <p ><strong >进阶:</strong >你能设计一个时间复杂度 <code >O(n)</code > 的解决方案吗?</p >
38
+
39
+ # 思路分析
40
+
41
+ 这种题一般就套一个有序数组就行。
42
+
43
+ O(n)的话就维护一下有序数组,使得数组中元素的个数不会大于三个。因为大于三个也用不到。
44
+
45
+ # Rust代码
46
+ ``` rust
47
+ # struct Solution ;
48
+ use std :: collections :: BTreeSet ;
49
+ impl Solution {
50
+ pub fn third_max (mut nums : Vec <i32 >) -> i32 {
51
+ let mut set = BTreeSet :: new ();
52
+ for item in nums {
53
+ set . insert (item );
54
+ }
55
+ * set . iter (). rev (). nth (2 ). unwrap_or (set . iter (). last (). unwrap ())
56
+ }
57
+ }
58
+ ```
Original file line number Diff line number Diff line change 6
6
- [ 2021力扣杯秋季编程大赛-战队赛复盘] ( ./special/leetcode-cup-2021-autumn-group.md )
7
7
- [ 2021年] ( ./2021/SUMMARY.md )
8
8
- [ 10月] ( ./2021/10/SUMMARY.md )
9
+ - [ 6日 - 第三大的数] ( ./2021/10/6-No.414.md )
9
10
- [ 5日 - 窥探迭代器] ( ./2021/10/5-No.284.md )
10
11
- [ 4日 - 密钥格式化] ( ./2021/10/4-No.482.md )
11
12
- [ 3日 - 分数到小数] ( ./2021/10/3-No.166.md )
You can’t perform that action at this time.
0 commit comments