题目:给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。
示例 1:
输入: [3, 2, 1]
输出: 1
解释: 第三大的数是 1.
示例 2:
输入: [1, 2]
输出: 2
解释: 第三大的数不存在, 所以返回最大的数 2 .
示例 3:
输入: [2, 2, 3, 1]
输出: 1
解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
存在两个值为2的数,它们都排第二。
解析:
①定义三个元素分别为初始前三大元素,first、second、third。它们的值均初始化为long类型的最小值Long.MIN_VALUE;
②遍历数组元素array[i],这里分三种情况:
a.如果array[i]大于first,则first=array[i],third=second,second=first。
b.如果array[i]在first和second之间,third=second,second=array[i]。
c.如果array[i]在second和third之间,third=array[i]。
这里分三种情况主要是为了在遍历数组后,first、second、third始终为前三大元素。
③最后只需要判断third这个数是否还为初始化值Long.MIN_VALUE,不为Long.MIN_VALUE则第三大数是third,返回third。否则没有第三大数,返回first即可。
public int thirdMax(int[] nums) {
long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE;
for (int i = 0; i < nums.length; i++){
if (nums[i] > first){
third = second;
second = first;
first = nums[i];
}else if(nums[i]>second&&nums[i]<first){
third = second;
second = nums[i];
}else if(nums[i]>third&&nums[i]<second){
third = nums[i];
}
}
return (int) ((third==Long.MIN_VALUE ) ? first:third);
}