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.

 

解法一:

 1 public class Solution {  
 2     /** 
 3      * @param nums: An integer array. 
 4      * @return: The second max number in the array. 
 5      */  
 6     public int secondMax(int[] nums) {  
 7         int first = Math.max(nums[0], nums[1]);  
 8         int second = Math.min(nums[0], nums[1]);  
 9           
10         for (int i = 2; i < nums.length; i++) {  
11             if (nums[i] > first) {  
12                 second = first;  
13                 first = nums[i];  
14             } else if (nums[i] > second) {  
15                 second = nums[i];  
16             }  
17         }  
18         return second;  
19     }  
20 } 

从数组前两位找到first大和second大的,从i=2开始遍历,不断找当前first大和second大。

 

相关文章:

  • 2021-07-02
  • 2021-11-02
  • 2022-02-11
  • 2021-10-24
  • 2021-11-10
  • 2021-07-01
  • 2021-11-11
  • 2021-09-02
猜你喜欢
  • 2021-06-10
  • 2021-05-26
  • 2021-06-14
  • 2021-05-19
  • 2021-12-22
  • 2021-07-30
  • 2021-04-02
相关资源
相似解决方案