414.第三大的数(javascript)414.ThirdMaximumNumber
原创给您一个非空数组并将其返回到此数组。 第三大数字 。如果不存在,则返回数组中最大的数字。
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
示例 1:
输入:[3, 2, 1]
输出:1
解释:第三大数字是 1 。
示例 2:
输入:[1, 2]
输出:2
解释:第三大数字不存在, 所以返回最大的数字 2 。
示例 3:
输入:[2, 2, 3, 1]
输出:1
解释:注意,要求返回第三大数字,是指在所有不同数字中排第三大数字。
本例中有两个值。 2 的数,它们都排第二。在所有不同数字中排第三大数字为 1 。
Example 1:
Input: nums = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
Example 2:
Input: nums = [1,2]
Output: 2
Explanation:
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: nums = [2,2,3,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2s are counted together since they have the same value).
The third distinct maximum is 1.
提示:
- 1 <= nums.length <= 104
-
-231 <= nums[i] <= 231 - 1
var thirdMax = function (nums) { //代码去重 var mySet = new Set(nums); let myArray = [...mySet] let len=myArray.length //按降序对代码进行排序 myArray.sort((a, b) => b - a) //第三大存在于列表下标中。2值,当下标不存在时返回该下标。0的值 return len <= 2?myArray[0]:myArray[2] };
以下是阵列的升序排列
myArray.sort((a, b) => a - b)
以下是数组的降序
myArray.sort((a, b) => b - a)
//此代码是对上述代码的优化。
var thirdMax = function (nums) {
var mySet = [...new Set(nums)].sort((a, b) => b - a);
return mySet[2]??mySet[0]
};
leetcode: https://leetcode-cn.com/problems/third-maximum-number/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123



