美文网首页
414. Third Maximum Number

414. Third Maximum Number

作者: 艾石溪 | 来源:发表于2016-11-24 21:12 被阅读7次

对于简单的问题,在联系不进行输出,直接写代码提交的方法。

题目:
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;
}
};

相关文章

网友评论

      本文标题:414. Third Maximum Number

      本文链接:https://www.haomeiwen.com/subject/sgcipttx.html