99클럽 코테 스터디 26일차 TIL
오늘의 학습 키워드
정렬
Easy
Topics
Companies
You are given an integer array score
of size n
, where score[i]
is the score of the ith
athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st
place athlete has the highest score, the 2nd
place athlete has the 2nd
highest score, and so on. The placement of each athlete determines their rank:
- The
1st
place athlete's rank is"Gold Medal"
. - The
2nd
place athlete's rank is"Silver Medal"
. - The
3rd
place athlete's rank is"Bronze Medal"
. - For the
4th
place to thenth
place athlete, their rank is their placement number (i.e., thexth
place athlete's rank is"x"
).
Return an array answer
of size n
where answer[i]
is the rank of the ith
athlete.
Example 1:
Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].
Example 2:
Input: score = [10,3,8,9,4]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].
Constraints:
n == score.length
1 <= n <= 104
0 <= score[i] <= 106
- All the values in
score
are unique.풀이 과정
- 입력받은 점수 리스트의 길이를 계산하여 저장한다
- 0부터
num_scores-1
까지의 인덱스를 담은 리스트를 생성한다 - 인덱스 리스트를 점수를 기준으로 정렬합니다.
lambda x: -scores[x]
는 각 인덱스에 해당하는 점수의 음수값을 반환하므로, 결과적으로 점수의 내림차순으로 정렬한다.- 상위 3개 순위에 대한 메달 명칭을 리스트로 저장한다.
- 결과를 저장할 리스트를 생성하고
None
으로 초기화한다. enumerate(indices)
로 각 인덱스와 해당 순위를 함께 처리한다.- 상위 3등까지는 메달 문자열을 할당한다.
- 4등 이하는 숫자 순위를 문자열로 변환하여 할당한다.
- 완성된 순위 리스트를 반환한다.
제출 코드 (python)
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
num_scores = len(score)
indices = list(range(num_scores))
indices.sort(key=lambda x: -score[x])
top_three_medals = ['Gold Medal', 'Silver Medal', 'Bronze Medal']
answer = [None] * num_scores
for rank, index in enumerate(indices):
if rank < 3:
answer[index] = top_three_medals[rank]
else:
answer[index] = str(rank + 1)
return answer
오늘의 회고
- heapq를 이용한 간단한 기본기 다지는 느낌이었다!
출처 : https://leetcode.com/problems/relative-ranks/description/