leetcode 414 Third Maximum Number

题目详情

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).

给定一个输入的数组,咱们须要找出这个数组中第三大的数,并且时间复杂度必须是o(n).若是不存在第三大的数,则返回最大的数。数组

思路

  • 由于时间复杂度为n,因此预排序是不能够的
  • 咱们必定要在一次遍历结束后就找到这个第三大的值。
  • 咱们能够直接设置三个变量来存储遍历过程当中所遇到的第1、2、三大的值。

解法

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;
    }
相关文章
相关标签/搜索