对于简单的问题,在联系不进行输出,直接写代码提交的方法。
题目:
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output:1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output:1
Explanation:Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
题目意思就不多解释了,看这几个例子已经很清楚了。
代码:
都是比较简单粗暴的方法,还没有想出其他的比较简洁的方法。
代码1
var thirdMax = function(nums) {
var firstMax = -Infinity, secondMax = -Infinity, thirdMax = -Infinity;
for(var x of nums){
if(x > firstMax){
firstMax = x;
}
}
for(var y of nums){
if(y > secondMax && y < firstMax){
secondMax = y;
}
}
for(var z of nums){
if(z > thirdMax && z < secondMax){
thirdMax = z;
}
}
if(isFinite(thirdMax)){
return thirdMax;
}else{
return firstMax;
}
};
代码2
var thirdMax = function(nums) {
var firstMax = -Infinity, secondMax = -Infinity, thirdMax = -Infinity;
for(var x of nums){
if(x > firstMax){
thirdMax = secondMax;
secondMax = firstMax;
firstMax = x;
}
if(x > secondMax && x < firstMax){
thirdMax = secondMax;
secondMax = x;
}
if(x > thirdMax && x < secondMax){
thirdMax = x;
}
}
if(isFinite(thirdMax)){
return thirdMax;
}else{
return firstMax;
}
};