LeetCode 506. Relative Ranks
점수가 가장 높은 순서대로 3명에게는 메달을 수여하고, 그 외에는 순위를 구한 값이 담긴 리스트를 반환한다.
문제 풀이
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 |
'온라인 코딩 테스트 문제 풀이 > LeetCode 문제 풀이' 카테고리의 다른 글
Python으로 푸는 LeetCode 965. Univalued Binary Tree (Easy) (0) | 2019.06.17 |
---|---|
Python으로 푸는 LeetCode 938. Range Sum of BST (Easy) (0) | 2019.06.14 |
Python으로 푸는 LeetCode 744. Find Smallest Letter Greater Than Target (Easy) (0) | 2019.05.15 |
Python으로 푸는 LeetCode 599. Minimum Index Sum of Two Lists (Easy) (0) | 2019.05.07 |