2017-08-11 10:40:16
1楼#1层
Python:
class Solution(object):
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
dmap = {v : k for k, v in enumerate(sorted(nums, reverse=True))}
return [str(dmap[n] + 1) \
if dmap[n] > 2 \
else ['Gold', 'Silver', 'Bronze'][dmap[n]] + ' Medal' for n in nums]
2017-08-11 10:40:47
2楼#1层
C++解法一:
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;
}
};
2017-08-11 10:41:09
3楼#1层
C++解法二:
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;
}
};
2017-08-11 10:41:30
4楼#1层
C++解法三:
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;
}
};