Q:
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.
A:
- Long.MIN_VALUE = -9223372036854775808 vs Integer.MIN_VALUE = -2147483648
当test case = [1, 2, -2147483648]时,应该返回-2147483648,这个值是第三大。但如果代码为return third == Integer.MIN_VALUE? first :third
,那么判断会成立而返回first值。因为当时初始化后,系统混淆了Integer.MIN_VALUE?和nums[2]的值。 -
continue;
只会结束current iteration,
而break;
直接move forward to next code block了。 - 一直track,top3 最大值,每一次都要比较,只要出现不同,就要进行替换。
public class Solution {
public int thirdMax (int[] nums) {
long first = Long.MIN_VALUE;
long second = Long.MIN_VALUE;
long third = Long.MIN_VALUE;
for (int i:nums){
if (i>first){
third = second;
second = first;
first = i;
}else if (i == first) //必要
continue;
else if (i > second){
third = second;
second = i;
}else if (i == second) //必要
continue;
else if (i > third){
third = i;
}
}
return third == Long.MIN_VALUE ? (int)first : (int)third;
//method 要求返回类型为int,强制转化一下,narrowing conversion
}
}
网友评论