leet code - 414. Third Maximum Number

임재현·2021년 3월 22일
0

코딩테스트준비

목록 보기
7/12

414. Third Maximum Number

Given integer array nums, return the third 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 third maximum is 1.

Example 2:

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

Example 3:

Input: nums = [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.

Constraints:

1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1

풀이 Runtime : 84ms, Memory : 41.7MB

var thirdMax = function(nums) {
    let s = new Set();
    let arr = [];
    for(let i = 0; i < nums.length; i++){
        s.add(nums[i]);
    }
    
    for(i of s){
        arr.push(i);
    }
    
    arr.sort((a,b) => b-a);
    
    if(arr[2] !== undefined) return arr[2];
    return Math.max(...arr);
};
profile
임재현입니다.

0개의 댓글

관련 채용 정보