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:
- N is a positive integer and won't exceed 10,000.
- All the scores of athletes are guaranteed to be unique.
這道題給了我們一組分數,讓我們求相對排名,前三名分別是金銀銅牌,后面的就是名次數,不是一道難題,我們可以利用堆來排序,建立一個優先隊列,把分數和其坐標位置放入隊列中,會自動按其分數高低排序,然后我們從頂端開始一個一個取出數據,由於保存了其在原數組的位置,我們可以直接將其存到結果res中正確的位置,用一個變量cnt來記錄名詞,前三名給獎牌,后面就是名次數,參見代碼如下:
解法一:
class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { int n = nums.size(), cnt = 1; vector<string> res(n, ""); priority_queue<pair<int, int>> q; for (int i = 0; i < n; ++i) { q.push({nums[i], i}); } for (int i = 0; i < n; ++i) { int idx = q.top().second; q.pop(); if (cnt == 1) res[idx] = "Gold Medal"; else if (cnt == 2) res[idx] = "Silver Medal"; else if (cnt == 3) res[idx] = "Bronze Medal"; else res[idx] = to_string(cnt); ++cnt; } return res; } };
下面這種方法思路和上面一樣,不過數據結構用的不同,這里利用map的自動排序的功能,不過map是升序排列的,所以我們遍歷的時候就要從最后面開始遍歷,最后一個是金牌,然后往前一次是銀牌,銅牌,名次數等,參見代碼如下:
解法二:
class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { int n = nums.size(), cnt = 1; vector<string> res(n, ""); map<int, int> m; for (int i = 0; i < n; ++i) { m[nums[i]] = i; } for (auto it = m.rbegin(); it != m.rend(); ++it) { if (cnt == 1) res[it->second] = "Gold Medal"; else if (cnt == 2) res[it->second] = "Silver Medal"; else if (cnt == 3) res[it->second] = "Bronze Medal"; else res[it->second] = to_string(cnt); ++cnt; } return res; } };
下面這種方法沒用什么炫的數據結構,就是數組,建立一個坐標數組,不過排序的時候比較的不是坐標,而是該坐標位置上對應的數字,后面的處理方法和之前的並沒有什么不同,參見代碼如下:
解法三:
class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { int n = nums.size(); vector<int> idx(n); vector<string> res(n, ""); for (int i = 0; i < n; ++i) idx[i] = i; sort(idx.begin(), idx.end(), [&](int a, int b){return nums[a] > nums[b];}); for (int i = 0; i < n; ++i) { if (i == 0) res[idx[i]] = "Gold Medal"; else if (i == 1) res[idx[i]] = "Silver Medal"; else if (i == 2) res[idx[i]] = "Bronze Medal"; else res[idx[i]] = to_string(i + 1); } return res; } };
參考資料:
https://discuss.leetcode.com/topic/77912/c-easy-to-understand
https://discuss.leetcode.com/topic/77876/easy-java-solution-sorting
https://discuss.leetcode.com/topic/78244/simple-c-solution-using-a-map
https://discuss.leetcode.com/topic/77869/simple-sorting-o-n-log-n-solution
