abc_begin

导航

479. Second Max of Array【easy】

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大。

 

posted on 2017-12-31 10:06  LastBattle  阅读(138)  评论(0编辑  收藏  举报