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.
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 2's are counted together since they have the same value). The third distinct maximum is 1.
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
var thirdMax = function(nums) { const _nums = new Set(nums) if (_nums.size <= 2) return Math.max(..._nums) return [..._nums].sort((a, b) => { return b - a })[2] };
這題麻煩之處在於,重複的數字不能列入排名。 當陣列是 [1, 2, 2] 時,必須回傳最大值,也就是 2。
我的做法是,先將所以重複的數字排除。 然後做排序,取得排第三的值。
不得不說 js 的內建 Set 真的很香,這邊複習一下基礎用法。
// 設定一個新的 Set , 它會幫你排除裡面重複的 value const mySet = new Set([1, 2, 2, 3]) // Set(3) {1, 2, 3} // 加個一新的值 mySet.add(4) // Set(4) {1, 2, 3, 4} // 刪除 mySet.delete(1) // Set(3) {2, 3, 4} // 取得數量 mySet.sizd // 3 // 判斷是否包含值 mySet.has(1) // false mySet.has(2) // true // 清除 mySet.clear() // Set(0) {size: 0}