[알고리즘] 백준 - 후보 추천하기

내 풀이

import sys
from collections import deque
from collections import defaultdict
sys.setrecursionlimit(100000)

N = int(input())
M = int(input())
arr = list(map(int, input().split()))
vote_list = []


def already_exist(newbie):
    for i in range(len(vote_list)):
        if vote_list[i][0] == newbie:
            return True
    return False


def add_vote(candidate):
    for i in range(len(vote_list)):
        if vote_list[i][0] == candidate:
            vote_list[i][1] += 1

for i in range(len(arr)):
    if len(vote_list) >= N and not already_exist(arr[i]):
        vote_list.sort(key = lambda x : (x[1], x[2]))
        vote_list.pop(0)
    if already_exist(arr[i]):
        add_vote(arr[i])
    else:
        vote_list.append([arr[i], 1, i])

ans = []
for candidate in vote_list:
    ans.append(candidate[0])

print(' '.join(map(str, sorted(ans))))

오랜만에 파이썬으로 문제를 풀어보려하니 낯설다.

좋은 웹페이지 즐겨찾기