Find the second max number in a given array.
Example
Example1:
Input: [1,3,2,4]
Output: 3
Example2:
Input: [1,1,2,2]
Output: 2
Notice
You can assume the array contains at least two numbers.
The second max number is the second number in a descending array.
思路:就是打擂台算法;比最大的大,顺序挪动,比第二的大,就赋值第二大的;刚开始取最小的Integer.MIN_VALUE;
public class Solution {
/**
* @param nums: An integer array
* @return: The second max number in the array.
*/
public int secondMax(int[] nums) {
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for(int num: nums) {
if(num > max) {
// 注意这里先把secondMax更新,再更新max;
secondMax = max;
max = num;
} else if(num > secondMax) {
secondMax = num;
}
}
return secondMax;
}
}