Notice
Recent Posts
Recent Comments
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- dacon
- PYTHON
- github
- leetcode
- Git
- 데이콘
- gs25
- hackerrank
- 캐치카페
- 프로그래머스 파이썬
- SW Expert Academy
- 우분투
- 파이썬
- programmers
- AI 경진대회
- 금융문자분석경진대회
- 프로그래머스
- ubuntu
- 자연어처리
- Baekjoon
- 백준
- 편스토랑 우승상품
- 코로나19
- Kaggle
- ChatGPT
- 편스토랑
- 맥북
- Docker
- Real or Not? NLP with Disaster Tweets
- 더현대서울 맛집
Archives
- Today
- Total
솜씨좋은장씨
[leetCode] 414. Third Maximum Number (Python) 본문
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
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
| [HackerRank] Counting Valleys (Python) (0) | 2020.03.07 |
|---|---|
| [HackerRank] Sock Merchant (Python) (0) | 2020.03.06 |
| [leetCode] 21. Merge Two Sorted Lists (Python) (0) | 2020.03.04 |
| [leetCode] 151. Reverse Words in a String (Python) (0) | 2020.03.03 |
| [BaeKJoon] 11656번: 접미사 배열 (Python) (0) | 2020.03.02 |
Comments