414.第三大的数

This commit is contained in:
游由 2022-02-22 18:35:19 +08:00
parent 6f8ed33ed5
commit 807a2e1404
2 changed files with 66 additions and 0 deletions

View File

@ -107,6 +107,7 @@ mod q0404;
mod q0405;
mod q0407;
mod q0412;
mod q0414;
mod q0415;
mod q0421;
mod q0424;

View File

@ -0,0 +1,65 @@
use crate::Solution;
impl Solution {
/// [414.第三大的数](https://leetcode-cn.com/problems/third-maximum-number/)
///
/// 2022-02-21 10:43:55
///
/// 给你一个非空数组,返回此数组中 **第三大的数** 。如果不存在,则返回数组中最大的数。
///
/// + **示例 1**
/// + **输入:** \[3, 2, 1\]
/// + **输出:** 1
/// + **解释:** 第三大的数是 1 。
/// + **示例 2**
/// + **输入:** \[1, 2\]
/// + **输出:** 2
/// + **解释:** 第三大的数不存在, 所以返回最大的数 2 。
/// + **示例 3**
/// + **输入:** \[2, 2, 3, 1\]
/// + **输出:** 1
/// + **解释:** 注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。
/// + **提示:**
/// * `1 <= nums.length <= 104`
/// * `-2^31 <= nums[i] <= 2^31 - 1`
/// + **进阶:**
/// 你能设计一个时间复杂度 `O(n)` 的解决方案吗?
/// + Related Topics
/// * 数组
/// * 排序
/// * 👍 339
/// * 👎 0
pub fn third_max(nums: Vec<i32>) -> i32 {
let (mut first, mut second, mut third) = (None, None, None);
for n in nums {
if first.is_none() || first.unwrap() < n {
third = second;
second = first;
first = Some(n);
} else if n < first.unwrap() && (second.is_none() || second.unwrap() < n) {
third = second;
second = Some(n);
} else if second.is_some() && n < second.unwrap() && (third.is_none() || third.unwrap() < n) {
third = Some(n);
}
}
match third {
Some(n) => n,
_ => first.unwrap()
}
}
}
#[cfg(test)]
mod test {
use crate::Solution;
#[test]
fn test_q0414() {
assert_eq!(Solution::third_max(vec![3, 2, 1]), 1);
assert_eq!(Solution::third_max(vec![1, 2]), 2);
assert_eq!(Solution::third_max(vec![2, 2, 3, 1]), 1);
assert_eq!(Solution::third_max(vec![2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 1]), 1);
assert_eq!(Solution::third_max(vec![1, 2, 2, 5, 3, 5]), 2);
}
}