Last active
September 9, 2019 06:12
-
-
Save shoark7/fa2e45c6523ecd52a44cde8963162d1b to your computer and use it in GitHub Desktop.
정수 배열에서 두 번째로 큰 값 찾기 in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""정수 배열에서 두 번째로 큰 값을 반환하라 | |
:입력: list of int | 정수 배열. 크기는 2 이상. (ex: [6, 5, 2, 1, 100, 3, 1, 59]) | |
:출력: int | 정수 배열의 2번째로 큰 정수. (ex: 59) | |
:조건: | |
1. list.sort() 함수를 쓰지 않는다. 이걸 쓰면 너무 쉽죠 사실... | |
2. 만약 최대값이 두 개 이상이면, 정답은 그것보다 작아야 한다.(ex: function([2, 2, 2, 1]) --> 1) | |
3. 만약 배열 내 모든 값이 똑같다면 두 번째 큰 값은 없기 때문에 'equality'라는 문자열을 출력한다. | |
""" | |
from math import inf | |
def second_largest(arr): | |
NO_ANSWER_MESSAGE = 'equality' | |
biggest = second = -inf | |
for n in arr: | |
if n > biggest: | |
second = biggest | |
biggest = n | |
elif second < n < biggest: | |
second = n | |
if second == -inf: | |
return NO_ANSWER_MESSAGE | |
else: | |
return second | |
############################################################################### | |
########################## 그게 최선입니까? 확실해요? ############################ | |
############################################################################### | |
def kth_biggest(arr, K): | |
# 예외 처리: K는 배열의 고유한 값 개수보다 클 수 없다. | |
ORDINAL_MSG = ('st', 'nd', 'rd')[K-1] if K <= 3 else 'th' | |
unique_set = set(arr) | |
if len(unique_set) < K: | |
raise IndexError(f"There's no {K}{ORDINAL_MSG} value in array") | |
elif K <= 0 or not arr: | |
raise ValueError("K should be over 0 and arr should not be empty") | |
# 상수 및 변수 선언 | |
INF = float('inf') | |
memory = [-INF] * K | |
# 실제 검색 연산 | |
for n in arr: | |
if n < memory[-1]: | |
continue | |
for i, m in enumerate(memory): | |
if (i == 0 and n > m) or m < n < memory[i-1]: | |
for j in range(len(memory)-2, i-1, -1): | |
memory[j+1] = memory[j] | |
memory[i] = n | |
break | |
return memory[-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment