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).若是不存在第三大的數,則返回最大的數。數組
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; }