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
- 맥북
- 코로나19
- Baekjoon
- Docker
- leetcode
- dacon
- 데이콘
- Git
- gs25
- 편스토랑
- 파이썬
- ChatGPT
- programmers
- 우분투
- AI 경진대회
- 프로그래머스 파이썬
- SW Expert Academy
- Kaggle
- 편스토랑 우승상품
- 금융문자분석경진대회
- 더현대서울 맛집
- 백준
- 캐치카페
- 프로그래머스
- ubuntu
- PYTHON
- github
- Real or Not? NLP with Disaster Tweets
- 자연어처리
- hackerrank
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 |