示例1给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。
输入:[3, 2, 1] 输出:1 解释:第三大的数是 1 。示例2
输入:[1, 2] 输出:2 解释:第三大的数不存在, 所以返回最大的数 2 。示例3
输入:[2, 2, 3, 1] 输出:1 解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。 此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为提示
- 1 <= nums.length <= 104
- -231 <= nums[i] <= 231 - 1
public int thirdMax(int[] nums) {
long first = Long.MIN_VALUE;
long second = Long.MIN_VALUE;
long third = Long.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
if (first < nums[i]) {
third = second;
second = first;
first = nums[i];
} else if (second < nums[i] && nums[i] < first) {
third = second;
second = nums[i];
} else if (third < nums[i] && nums[i] < second) {
third = nums[i];
}
}
if (third == Long.MIN_VALUE)
return (int) first;
return (int) third;
}



