1. 题目原址
https://leetcode.com/problems/third-maximum-number/
2. 题目描述
3. 题目大意
给定一个数组,返回数组中第三大的元素
4. 解题思路
- 定义三个变量,分别存储数组中前三大的元素。
- 通过增强for循环来遍历数组中的元素,然后根据 if 语句来判断当前元素是否是前三大的元素
5. AC代码
class Solution {
public int thirdMax(int[] nums) {
long max = Long.MIN_VALUE;
long second = Long.MIN_VALUE;
long third = Long.MIN_VALUE;
for(int i : nums) {
if(i > max) {
third = second;
second = max;
max = i;
}else if(i > second && i < max) {
third = second;
second = i;
}else if(i > third && i < second) {
third = i;
}
}
return (int) (third == Long.MIN_VALUE?max:third);
}
}
6. 相关题目
【1】 215. Kth Largest Element in an Array https://leetcode.com/problems/kth-largest-element-in-an-array/