아이공의 AI 공부 도전기

[Baekjoon] 1302번 : 베스트셀러 (Python, 문자열, 정렬, 해시)

 

     

 

 

 

https://www.acmicpc.net/problem/1302

 

1302번: 베스트셀러

첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고

www.acmicpc.net

코드 링크

https://github.com/stellaluminary/Baekjoon

 

GitHub - stellaluminary/Baekjoon

Contribute to stellaluminary/Baekjoon development by creating an account on GitHub.

github.com

 

Python

 

방법 1 - 메모리 30840KB / 시간 68ms / 코드 길이 308B

 

dict 해시를 통한 저장과 함께 최빈 값에 따른 사전순 정렬을 진행한 후 값을 도출한다.

 

import sys
input = sys.stdin.readline

n = int(input())
l = [input().rstrip() for _ in range(n)]
d = {}
max_n = 0
for i in l:
    if i not in d:
        d[i] = 1
    else:
        d[i] += 1
    max_n = max(max_n, d[i])

res = []

for i in d:
    if d[i] == max_n:
        res.append(i)

print(sorted(res)[0])

 

 

방법 2 - 메모리 30840KB / 시간 76ms / 코드 길이 263B

 

dict를 활용하는 것이 가장 깔끔하지만 만약 list로만 한다면 다음과 같이 코드를 짤 수 있다.

 

 

import sys
input = sys.stdin.readline

n = int(input())
l = [input().rstrip() for _ in range(n)]
unique = []
for i in l:
    if i not in unique:
        unique.append(i)

num = sorted([(l.count(i),i) for i in unique], key=lambda x:(-x[0], x[1]))

print(num[0][1])

 

 

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading