Problem
Solution
Initial thoughts
Python implementation
1 2 3 4 5 6 7 8 9
|
class : def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ ranks = {num:r+1 for r, num in enumerate(sorted(nums, reverse=True))} map_rank = lambda r : ["Gold Medal", "Silver Medal", "Bronze Medal"][r-1] if r <= 3 else str(r) return [map_rank(ranks[num]) for num in nums]
|
Java implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class { public String[] findRelativeRanks(int[] nums) { int[] c_nums = nums.clone(); Arrays.sort(c_nums); Map<Integer, Integer> ranks = new HashMap<>(); for(int i = c_nums.length - 1; i >= 0; i--){ ranks.put(c_nums[i], c_nums.length-i); } String[] medals = {"Gold Medal", "Silver Medal", "Bronze Medal"}; String[] ans = new String[nums.length]; for(int i = 0; i < nums.length; i++){ int num = nums[i]; int r = ranks.get(num); if(r<=3){ ans[i] = medals[r-1]; }else{ ans[i] = r+""; } } return ans; } }
|
Time complexity
O(nlogn).
Space complexity
O(n).
Links
506. Relative Ranks
(中文版) 算法笔记: 力扣#506 相对名次
近期评论