Algorithm
[프로그래머스] 명예의 전당 (1)
쑤야.
2024. 3. 14. 08:10
https://school.programmers.co.kr/learn/courses/30/lessons/138477
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
접근
- k는 최대 100, score 배열의 크기는 최대 1000
- 명예의 전당을 관리하기 위해서는 정렬이 필요
- 최악의 시간 복잡도인 1000 * 100 log 100은 시간 초과가 되지 않음
- score 반복문 안에서 매번 정렬을 수행해도 괜찮음
코드
1. Swift 풀이
func solution(_ k:Int, _ score:[Int]) -> [Int] {
var answer = [Int]()
var board = [Int]()
for s in score {
if board.count < k {
board.append(s)
}
else if board.last! < s {
board[k-1] = s
}
board.sort(by: >)
answer.append(board.last!)
}
return answer
}
2. Python 풀이
def solution(k, score):
answer = []
board = []
for s in score:
if len(board) < k :
board.append(s)
elif board[-1] < s:
board[k-1] = s
board.sort(reverse=True)
answer.append(board[-1])
return answer