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

  • 相关阅读:
    2020.12.15
    2020.12.14
    2020.12.13
    2020.12.11
    2020.12.10
    语音合成标记语言(SSML)
    Skyline查询
    win10 VMware 安装 Linux 虚拟机
    图像梯度计算
    Harris Corner Detection
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8157141.html
Copyright © 2020-2023  润新知