414. Third Maximum Number
Easy
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.
package leetcode.easy; public class ThirdMaximumNumber { @org.junit.Test public void test() { int[] nums1 = { 3, 2, 1 }; int[] nums2 = { 1, 2 }; int[] nums3 = { 2, 2, 3, 1 }; System.out.println(thirdMax(nums1)); System.out.println(thirdMax(nums2)); System.out.println(thirdMax(nums3)); } public int thirdMax(int[] nums) { int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE; boolean minPresent = false; for (int n : nums) { if (n == Integer.MIN_VALUE) { minPresent = true; } if (n > max1) { max3 = max2; max2 = max1; max1 = n; } else if (n > max2 && n < max1) { max3 = max2; max2 = n; } else if (n > max3 && n < max2) { max3 = n; } } if (max3 != Integer.MIN_VALUE) { return max3; } else { if (minPresent && max2 != Integer.MIN_VALUE) { return max3; } else { return max1; } } } }