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;
    }
相關文章
相關標籤/搜索