美文网首页
Third Maximum Number

Third Maximum Number

作者: ibyr | 来源:发表于2017-02-12 13:37 被阅读9次
Question

Given a non-empty array of integers, return the third maximum number in this array. If it does not exists, return the maximum number. The time complexity must be in O(n).

Note
  • 设置3个临时变量,分别存储max1, max2, max3。也可以是一个长度为3的数组。
Extension
  • 求第k大的数(k < 5, k值变大,求解效率变低。),都可以使用这个方法来求解。
  • 堆排序雏形。求第k大(小),可以建立k长的大顶堆(小顶堆)。
  • Java中,PriorityQueue是用数组的形式实现了二叉小顶堆。
Solution
public int thirdMax(int[] nums) {
    Integer max1 = null;
    Integer max2 = null;
    Integer max3 = null;
    for (Integer n : nums) {
        if (n.equals(max1) || n.equals(max2) || n.equals(max3)) {
            continue;
        }
        if (max1 == null || n > max1) {
            max3 = max2;
            max2 = max1;
            max1 = n;
        } else if (max2 == null || n > max2) {
            max3 = max2;
            max2 = n;
        } else if (max3 == null || n > max3) {
            max3 = n;
        }
    }
    return max3 == null ? max1 : max3;
}
// 注:此解法非原创,只供提供学习思路。

相关文章

网友评论

      本文标题:Third Maximum Number

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