본문으로 바로가기

 

 LeetCode 506. Relative Ranks 

점수가 가장 높은 순서대로 3명에게는 메달을 수여하고, 그 외에는 순위를 구한 값이 담긴 리스트를 반환한다.

LeetCode에서 푼 문제 리스트 보기

LeetCode에서 문제 보기

Github에서 코드 보기

문제 풀이

nums를 역순으로 정렬한 리스트 sorted_nums를 생성한다. sorted_nums에서부터 값을 하나씩 꺼내게 되면 해당 점수의 순위를 알 수 있다. index 2까지의 점수는 순위가 아닌 medal을 받아야 한다. 따라서 medal 리스트로부터 index를 활용해 어떤 메달을 받게 될지 구한다. 그 외에는 index + 1 한 값이 순위이므로 그 값을 nums에 추가시킨다.

파이썬 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def findRelativeRanks(self, nums):
        sorted_nums = sorted(nums, reverse=True)
        medal = ["Gold Medal""Silver Medal""Bronze Medal"]
        # result = [0]*len(sorted_nums)
        i = -1
        for n in sorted_nums:
            i += 1
            idx = nums.index(n)
            if i < 3:
                nums[idx] = medal[i]
                continue
            nums[idx] = str(i + 1)
        return nums
cs