414. Third Maximum Number
Problem:
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.
Analysis:
这道题真垃圾,毫无技术含量。有人用一次循环,三个变量来做,头都看晕了,easy的题何必呢。Test case居然有Integer.MIN_VALUE,非得用long转换一下。
Solution:
class Solution { public int thirdMax(int[] nums) { if (nums == null || nums.length == 0) return 0; long max = Long.MIN_VALUE, secMax = Long.MIN_VALUE, thirdMax = Long.MIN_VALUE; for (int i: nums) { max = Math.max(i, max); } for (int i : nums) { if (i != max) { secMax = Math.max(i, secMax); } } for (int i: nums) { if (i != max && i != secMax) { thirdMax = Math.max(i, thirdMax); } } return thirdMax == Long.MIN_VALUE ? (int)max : (int)thirdMax; } }
评论
发表评论