题目摘要
给定一个非空数组,找出其中第三大的数,如果没有,找出其中最大的数。时间复杂度必须控制在
O(n)
内。
解法
int max, mid, min,赋值为整形最小值。遍历数组,按大小情况替换max, mid, min, 最后判断有没有第三大的数,返回。
public class Solution {
public int thirdMax(int[] nums) {
int max, mid, min;
max = mid = min = Integer.MIN_VALUE;
//检查nums中是否有Integer.MIN_VALUE;
boolean hasMin = false;
for (int x : nums) {
if (x == Integer.MIN_VALUE) hasMin = true;
if (x == max || x == mid) continue;
if ( x > max) {
min = mid;
mid = max;
max = x;
} else if (x > mid) {
min = mid;
mid = x;
} else if (x > min) {
min = x;
}
}
if (mid == Integer.MIN_VALUE) {
return max;
} else if (min == Integer.MIN_VALUE) {
if (hasMin) return min;
else return max;
} else {
return min;
}
}
}
注意
- 如何判断有没有第三大的数
在遍历的同时检查数组里有没有Integer.MIN_VALUE
,再结合max, mid, min
中有没有该值来判断据此来判断。
可问问题
原题
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.