leetCode刷题记录52_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).
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.
给定一个非空整数数组,返回第3大的元素,如果不存在,则返回最大的数字
/*****************************************************我的解答*************************************************
/**
 * @param {number[]} nums
 * @return {number}
 */
var thirdMax = function(nums) {
    //先去除重复
    var    tempArray = Array.from(new Set(nums));
    tempArray.sort((a,b) => a - b);
    if(tempArray.length <= 2)
    {
        return Math.max.apply(null,tempArray);
    }    
    else
    {
        return tempArray[tempArray.length - 3];
    }    
};

发布了135 篇原创文章 · 获赞 10 · 访问量 6373

猜你喜欢

转载自blog.csdn.net/gunsmoke/article/details/88819842