题目:
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 exceed10,000
.
All the scores of athletes are guaranteed to be unique.
解释:
先用一个字典记录原始的值所在的位置,然后降序排序,这样不用每次都用index()
求索引值,真的要学会使用dict来省时间啊。
python暴力解法:
class Solution(object):
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
result=['0']*len(nums)
sort_nums=sorted(nums)[::-1]
flag_g=0
for i in xrange(len(nums)):
index=sort_nums.index(nums[i])
if index>2:
result[i]=str(index+1)
elif index==0:
result[i]="Gold Medal"
elif index==1:
result[i]="Silver Medal"
else:
result[i]="Bronze Medal"
return result
稍微优美一点的代码:
class Solution(object):
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
result=['0']*len(nums)
n=len(nums)
_dict={}
for i in range(n):
_dict[nums[i]]=i
sorted_nums=sorted(nums,reverse=True)
for i in range(n):
target_index=_dict[sorted_nums[i]]
if i==0:
result[target_index]="Gold Medal"
elif i==1:
result[target_index]="Silver Medal"
elif i==2:
result[target_index]="Bronze Medal"
else:
result[target_index]=str(i+1)
return result
实际上,一个是对result按顺序修改,另一个是按排好序的数字一个个该其在result中对应的位置的值,角度不同而已,但是查dict比index()
要快是真的。
c++代码:
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
int n=nums.size();
vector<string> result(n,"");
map<int,int>_map;
for(int i=0;i<n;i++)
_map[nums[i]]=i;
vector<int>sorted_nums(nums.begin(),nums.end());
//降序排序
sort(sorted_nums.begin(),sorted_nums.end(),greater<int>());
for(int i=0;i<n;i++)
{
int target_index=_map[sorted_nums[i]];
if(i==0)
result[target_index]="Gold Medal";
else if(i==1)
result[target_index]="Silver Medal";
else if(i==2)
result[target_index]="Bronze Medal";
else
result[target_index]=to_string(i+1);
}
return result;
}
};
总结:
stl中降序排序不一定非要 sort()
后reverse()
,可以sort(sorted_nums.begin(),sorted_nums.end(),greater<int>());