Formatted question description:

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

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.


Use three variables to store the three distinct maximum numbers. Also use a variable to store the count of distinct numbers in the array. Initially, the three variables for three maximum numbers are Long.MIN_VALUE, where data type long is used to avoid overflow.

Loop over the array. Use the idea of insertion sort and update the three distinct maximum numbers. If the current number is greater than at least one of the three distinct maximum numbers, then update the distinct maximum numbers that has a smaller value, and increase the counter by 1.

Finally, if the counter is greater than or equal to 3, return the third distinct maximum number. Otherwise, return the first maximum number.

class Solution {
    public int thirdMax(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        long firstMax = Long.MIN_VALUE;
        long secondMax = Long.MIN_VALUE;
        long thirdMax = Long.MIN_VALUE;
        int count = 0;
        for (int num : nums) {
            long numLong = (long) num;
            if (numLong == firstMax || numLong == secondMax || numLong == thirdMax)
            if (numLong > firstMax) {
                thirdMax = secondMax;
                secondMax = firstMax;
                firstMax = numLong;
            } else if (numLong > secondMax) {
                thirdMax = secondMax;
                secondMax = numLong;
            } else if (numLong > thirdMax) {
                thirdMax = numLong;
        return count >= 3 ? (int) thirdMax : (int) firstMax;

All Problems

All Solutions