본문 바로가기

Algorithm & Data Structure

백준 - 2108번

728x90
반응형
from collections import Counter
import math
import sys

count = int(sys.stdin.readline())

num_array = []

for i in range(count):
    t = int(sys.stdin.readline())
    num_array.append(int(t))

print(round(sum(num_array)/count)) #산술평균

num_array.sort()

print(num_array[math.floor(count/2)]) #중앙값

#최빈값
temp_arr =[]
cnt = Counter(num_array).most_common()

for i in range (len(cnt)):
    if(cnt[0][1]==cnt[i][1]):
        temp_arr.append(cnt[i][0])
    else: break

if len(temp_arr) == 1:
    print(temp_arr[0]) #최빈값
else:
    print(temp_arr[1])  #최빈값

print(num_array[count-1] - num_array[0]) #범위

정답률 26퍼센트에 쫄았던 문제다.

합불을 가르는건 다름 아닌 sys.stdin.readline() 이였다.

input()을 사용하면 시간초과가 나는 경우가 여럿있다.

sort() 보다는 내가 위에 for문을 사용하여 만든 정렬 방식이 속도가 빠른듯 하다.

최빈값을 제외한 나머지는 오름차순 정렬만 제대로 하고나면 어려울것이 전혀 없다.

최빈값은 2차원 배열에 [반복횟수, 요소 값]을 넣어주는 counter 함수를 사용했다.

728x90
반응형

'Algorithm & Data Structure' 카테고리의 다른 글

백준 - 15649번  (0) 2022.01.09
DFS & BFS  (0) 2022.01.08
백준 - 1002번  (0) 2021.12.23
백준 - 4948번  (0) 2021.12.23
백준 - 2581번  (0) 2021.12.21