Given a non-empty array of integers, returnthe third maximum number in this array. If it does not exist, return themaximum number. The time complexity must be in O(n).
翻译:给一个非空的数组,求第三大的数。若不存在返回最大值。
析:直接进行排序,从后往前,遍历一遍就好,代码如下
public class Solution {
public int thirdMax(int[] nums) {
Arrays.sort(nums);
intlength=nums.length-1;
intthirdMax=nums[length];
intcount=0;
for(inti=length-1;i>=0;i--){
if(thirdMax>nums[i]){
thirdMax=nums[i];
count++;
}
if(count==2){
break;
}
}
if(count!=2)thirdMax=nums[length];
returnthirdMax;
}
}