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.
这一题咋看之下非常简单,实际上也特别简单,但是感觉有几个坑要注意。
- 它说如果数组不到3个数字的话,就返回最大值。
- 如果出现两个相同的值的话,算一个。其实这个还给我们带来简便,如果相同值不算一个的话,更麻烦,因为这样需要先算前三个数的大小。这样就不用算了,反正不可能出现重复的。
- 他的测试用例中,有个极端例子,-2147483648,这个是int的最小值,所以代码中可能不能使用int了,要考虑升级。
public class Solution {
public int thirdMax(int[] nums) {
double nFirst = Double.NEGATIVE_INFINITY;
double nSecond = Double.NEGATIVE_INFINITY;
double nThird = Double.NEGATIVE_INFINITY;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > nThird) {
if (nums[i] < nSecond) {
nThird = nums[i];
} else if (nums[i] > nSecond && nums[i] < nFirst) {
nThird = nSecond;
nSecond = nums[i];
} else if (nums[i] > nFirst) {
nThird = nSecond;
nSecond = nFirst;
nFirst = nums[i];
}
}
}
return (int) (nThird == Double.NEGATIVE_INFINITY ? nFirst : nThird);
}
}
最后,作为菜鸟的我发现一个以前没有注意到的点,就是Double.MIN_VALUE和Integer.MIN_VALUE的定义的不一样。它定义的是最小的正数,也就是说小数点后最精确的位数,所以这里使用的是Double.NEGATIVE_INFINITY。
/** * A constant holding the positive infinity of type * {@code double}. It is equal to the value returned by * {@code Double.longBitsToDouble(0x7ff0000000000000L)}. */ public static final double POSITIVE_INFINITY = 1.0 / 0.0; /** * A constant holding the negative infinity of type * {@code double}. It is equal to the value returned by * {@code Double.longBitsToDouble(0xfff0000000000000L)}. */ public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
/** * A constant holding the largest positive finite value of type * {@code double}, * (2-2<sup>-52</sup>)·2<sup>1023</sup>. It is equal to * the hexadecimal floating-point literal * {@code 0x1.fffffffffffffP+1023} and also equal to * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}. */ public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308 /** * A constant holding the smallest positive normal value of type * {@code double}, 2<sup>-1022</sup>. It is equal to the * hexadecimal floating-point literal {@code 0x1.0p-1022} and also * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}. * * @since 1.6 */ public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308 /** * A constant holding the smallest positive nonzero value of type * {@code double}, 2<sup>-1074</sup>. It is equal to the * hexadecimal floating-point literal * {@code 0x0.0000000000001P-1022} and also equal to * {@code Double.longBitsToDouble(0x1L)}. */ public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324