관리 메뉴

솜씨좋은장씨

[leetCode] 414. Third Maximum Number (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 414. Third Maximum Number (Python)

솜씨좋은장씨 2020. 3. 5. 16:30
728x90
반응형

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.

 

Solution

class Solution:
    def thirdMax(self, nums):
        nums = list(set(nums))
        
        nums = list(sorted(nums, reverse=True))
        
        if len(nums) < 3:
            answer = nums[0]
        else:
            answer = nums[2]
        return answer

Solution 풀이

nums를 set으로 바꿨다가 list로 바꾸어 중복값 제거

sorted함수에서 reverse = True를 적용하여 내림차순으로 정렬

만약 nums의 길이가 3 미만이면 3번째로 큰 숫자가 없으므로 가장 큰 수를 답으로

3이상이면 3번째 숫자를 답으로 return 하도록 합니다.

 

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments