Find the second max number in a given array.
Notice
You can assume the array contains at least two numbers.
Example
Given [1,
3, 2, 4], return 3.
Given [1,
2], return 1.
思路:从数组前两位找到first大和second大的,从i=2开始遍历,不断找当前first大和second大,因此是O(n)
public class Solution {
/**
* @param nums: An integer array.
* @return: The second max number in the array.
*/
public int secondMax(int[] nums) {
int first=Math.max(nums[0],nums[1]);
int second=Math.min(nums[0],nums[1]);
for(int i=2;i<nums.length;i++){
if(nums[i]>first){
second=first;
first=nums[i];
}else if(nums[i]>second){
second=nums[i];
}
}
return second;
}
}
本文介绍了一种高效算法,用于查找给定数组中的第二大数值。通过一次遍历即可完成,时间复杂度为O(n)。

1万+

被折叠的 条评论
为什么被折叠?



