414. Third Maximum Number

Description

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.

Solution

Sort, time O(nlogn), space O(1)

class Solution {
    public int thirdMax(int[] nums) {
        Arrays.sort(nums);
        int i = nums.length - 2;
        int distinctNumCount = 1;
        
        while (i >= 0) {
            if (nums[i] != nums[i + 1] && ++distinctNumCount == 3) {
                break;
            }
            --i;
        }
        
        return i >= 0 ? nums[i] : nums[nums.length - 1];
    }
}

Count, time O(n), space O(1)

class Solution {
    public int thirdMax(int[] nums) {
        long max1 = Long.MIN_VALUE; // in case nums include Integer.MIN_VALUE
        long max2 = Long.MIN_VALUE;
        long max3 = Long.MIN_VALUE;
        
        for (int n : nums) {
            if (n == max1 || n == max2 || n == max3) {
                continue;
            }
            
            if (n > max1) {
                max3 = max2;
                max2 = max1;
                max1 = n;
            } else if (n > max2) {
                max3 = max2;
                max2 = n;
            } else if (n > max3) {
                max3 = n;
            }
        }
        
        return max3 != Long.MIN_VALUE ? (int) max3 : (int) max1;
    }
}

你可能感兴趣的:(414. Third Maximum Number)