问题:
难度easy
说明:
从一个输入的数组里面找到,第三个是数组内最大的数字,如果数组长度小于3,就返回第一最大的数字。
输入输出案例:
// 1是第三个数组内最大的
Input: [3, 2, 1]
Output: 1
// 因为没有第三个,所以返回2,数组内最大的
Input: [1, 2]
Output: 2
我的代码:
想过用hash排序或者用minstack那种解法,不过都没结果,还只能是固定的解题思路。来三个变量,然后判断处理,不过坏处就是如果题目改成求第N个最大数,变量会不会太多(用数组似乎也可以)。
class Solution {
public int thirdMax(int[] nums) {
// 命名三个变量,因为long可以概括int取值范围,所以使用long
long max = Long.MIN_VALUE;
long temp01 = Long.MIN_VALUE;
long temp02 = Long.MIN_VALUE;
// 进行区分(temp02, temp01), (temp01, max),(max, + ∞)
for(int i = 0;i < nums.length;i ++) {
int n = nums[i];
if(max < n) {
temp02 = temp01;
temp01 = max;
max = nums[i];
} else if(temp01 < n && max > n) {
temp02 = temp01;
temp01 = nums[i];
} else if(temp02 < n && temp01 > n) {
temp02 = nums[i];
}
}
// 检查temp02是否未赋值,或者temp02和temp01未赋值
return (temp02 == Long.MIN_VALUE || temp02 == temp01) ? (int)max : (int)temp02;
}
}
和别人没什么特别解题思路。