506. Relative Ranks

題目:

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

Example 1:

Input:  [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". 
For the left two athletes, you just need to output their relative ranks according to their scores.

Note:

  1. N is a positive integer and won't exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.

思路:

用一個hash來儲存原始nums的index,把nums排序後存到另一個陣列裡,再用來的陣列來找前三高值利用map找到index再把前三名的獎牌存進去

pseudocode:

建立一個空的hash預設值是0
檢查s和t字串,如果是空或者長度不相同,回傳false
從s的第一個字母開始到最後一個字母
如果s的字母為key在hash裏的值是0,就把t的字母存進去當值
如果s的字母為key在hash裏的值是不是t的對應字母,就回傳false
全部跑完都沒有回傳false,就回傳true

使用到的語法:

sort
reverse

程式碼:

def find_relative_ranks(nums)
  map = {}
  nums.each_with_index do |n,i|
    map[n] = i
  end
  record = nums.sort.reverse
  record.each_with_index do |n,i|
    nums[map[n]] = 'Gold Medal' if i == 0
    nums[map[n]] = 'Silver Medal' if i == 1
    nums[map[n]] = 'Bronze Medal' if i == 2
    nums[map[n]] = (i+1).to_s if i > 2
  end
  return nums
end

results matching ""

    No results matching ""