zoukankan      html  css  js  c++  java
  • 414. Third Maximum Number

    Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

    给定一个非空数组的整数,返回该数组中的第三个最大数。 如果不存在,返回最大数量。 时间复杂度必须在O(n)中。

    Example 1:

    Input: [3, 2, 1]
    
    Output: 1
    
    Explanation: The third maximum is 1.
    

    Example 2:

    Input: [1, 2]
    
    Output: 2
    
    Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
    

    Example 3:

    Input: [2, 2, 3, 1]
    
    Output: 1
    
    Explanation: Note that the third maximum here means the third maximum distinct number.
    Both numbers with value 2 are both considered as second maximum.

    思路其实很简单,设置三个变量,first second third 分别存储前三大数,遍历数组,找到前3大数,根据不同情况将nums[i]和first second third 进行替换,
    最后返回最大值或者第三大数;
    var thirdMax = function(nums) {
        var len = nums.length;
        var first,second,third;
        if(len < 3){
            third = Math.max.apply(Math,nums);
        }else{
           
            first = nums[0];
            for(var i = 1;i < len;i++){
                if(second === undefined){
                    if(nums[i] < first){
                    second = nums[i];
                }else if(nums[i] > first){
                    second = first;
                    first = nums[i];
                }
                }else if(second !== undefined && third === undefined){
                    if(nums[i] < second){
                        third = nums[i];
                    }else if(nums[i] > first){
                        third = second;
                        second = first;
                        first = nums[i];
                    }else if(nums[i] > second && nums[i] < first){
                        third = second;
                        second = nums[i];
                    }
                }else if(second !== undefined && third !== undefined){
                    if(nums[i] > third && nums[i] < second){
                    third = nums[i];
                }else if(nums[i] > second && nums[i] < first){
                    third = second;
                    second = nums[i];
                }else if(nums[i] > first){
                    third = second;
                    second = first;
                    first = nums[i];
                }
                }
                
            }
         }   
            if(third === undefined){
                return first;
            }else {
                return third;
            }
      
    };
  • 相关阅读:
    第三章 达瑞,一个很能挣钱的男孩
    入门代码教程第一节 如何:定义服务协定
    第二节 Windows Communication Foundation 基础概念
    入门代码教程第四节 如何:创建客户端
    BZOJ:2186: [Sdoi2008]沙拉公主的困惑
    DNN学习笔记代码学习:Provider 荣
    DNN学习笔记代码学习:DataCache 荣
    DNN学习笔记代码学习:ProviderConfiguration 荣
    DNN学习笔记代码学习:Reflection 荣
    java动态加载类
  • 原文地址:https://www.cnblogs.com/deerfig/p/6680388.html
Copyright © 2011-2022 走看看