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 the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").
Return an array answer of size n where answer[i] is the rank of the ith athlete.
입출력 예 설명
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].
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].
💻내가 짠 코드
class Solution:
def findRelativeRanks(self, score):
sorted_score = sorted(score, reverse=True)
rank_dict = {}
for i, s in enumerate(sorted_score):
if i == 0:
rank_dict[s] = "Gold Medal"
elif i == 1:
rank_dict[s] = "Silver Medal"
elif i == 2:
rank_dict[s] = "Bronze Medal"
else:
rank_dict[s] = str(i + 1)
return [rank_dict[s] for s in score]
# 테스트 실행
solution = Solution()
score = [5,4,3,2,1]
print(solution.findRelativeRanks(score)) # 출력: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
✍ 접근 방법
-
- 점수를 내림차순 정렬 → sorted_score
- 각 점수에 등수 매핑 → rank_dict (딕셔너리 사용)
- 1~3등은 메달 이름으로 변경
- 원래 점수 순서대로 순위 반환
'Study > Python' 카테고리의 다른 글
[99클럽 코테 스터디] 19일차 TIL - 절댓값 힙 (0) | 2025.02.14 |
---|---|
[99클럽 코테 스터디] 18일차 TIL - 크리스마스 선물 (0) | 2025.02.12 |
[99클럽 코테 스터디] 15일차 TIL - 균형잡힌 세상 (0) | 2025.02.07 |
[99클럽 코테 스터디] 14일차 TIL - 식당 메뉴 (0) | 2025.02.06 |
[99클럽 코테 스터디] 13일차 TIL - 큐 (0) | 2025.02.06 |