https://www.acmicpc.net/problem/11652
준규는 숫자 카드 N장을 가지고 있다. 숫자 카드에는 정수가 하나 적혀있는데, 적혀있는 수는 보다 크거나 같고, 보다 작거나 같다.
준규가 가지고 있는 카드가 주어졌을 때, 가장 많이 가지고 있는 정수를 구하는 프로그램을 작성하시오. 만약, 가장 많이 가지고 있는 정수가 여러 가지라면, 작은 것을 출력한다.
Code 1
n = int(input())
cards = {}
max_cnt = 0
result = 2**62
for i in range(n):
m = int(input())
if m not in cards.keys():
cards[m] = 0
cards[m] += 1
if max_cnt < cards[m]:
max_cnt = cards[m]
result = m
if (max_cnt == cards[m]) and result > m:
result = m
print(result)
Code 2
n = int(input())
cards = {}
for i in range(n):
m = int(input())
if m not in cards.keys():
cards[m] = 0
cards[m] += 1
result = sorted(cards.items(), key=lambda x: (-x[1], x[0]))
print(result[0][0])
참고
위와 같은 방법으로 sorted()
로 dictionary도 정렬 가능하다