[
sort
hash table
]
Leetcode 0506 Relative Ranks
Problem statement
https://leetcode.com/problems/relative-ranks/
Solution
Just sort numbers, keeping original indexes. Then traverse sorted array, and put everyone on its place.
Complexity
Time complexity is O(n log n)
, space complexity is O(n)
.
Code
class Solution:
def findRelativeRanks(self, nums):
n = len(nums)
pairs = sorted(zip(nums, range(n)), reverse = True)
out = [0]*n
medals = {0: "Gold", 1: "Silver", 2: "Bronze"}
for i, (j, k) in enumerate(pairs):
out[k] = medals[i] + " Medal" if i <= 2 else str(i + 1)
return out