分数越高的选手,排名越靠前。 
   数据范围 
   0<=N<=105
 
 [5, 4, 3, 2, 1]
["Gold Medal","Silver Medal","Bronze Medal","4","5"]
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param score int整型vector 运动员成绩
     * @return string字符串vector
     */
    static bool cmp(int a, int b){
        return a > b;
    }
    vector<string> findRelativeRanks(vector<int>& score) {
        // write code here
        vector<int> sortedScore = score;
        sort(sortedScore.begin(), sortedScore.end(), cmp);
        unordered_map<int, string> map;
        for(int i = 0; i < score.size(); i++){
            if(i == 0){
                map[sortedScore[i]] = "Gold Medal";
            }else if(i == 1){
                map[sortedScore[i]] = "Silver Medal";
            }else if(i == 2){
                map[sortedScore[i]] = "Bronze Medal";
            }else{
                map[sortedScore[i]] = to_string(i + 1);
            }
        }
        vector<string> result;
        for(int i = 0; i < score.size(); i++) result.push_back(map[score[i]]);
        return result;
    }
}; class Solution: def findRelativeRanks(self , score ): tmp = sorted(list(set(score))) # 去重排序 tmp = dict(zip(tmp, list(range(len(tmp), 0, -1)))) # 每个元素的索引(名次,从1开始) res = [str(tmp[i]) for i in score] # 根据分数排名次 for i in range(len(score)): if res[i] == '1': res[i] = 'Gold Medal' if res[i] == '2': res[i] = 'Silver Medal' if res[i] == '3': res[i] = 'Bronze Medal' return res这个题的关键点在于得分相同名次也一定相同,所以先去重再排序即可得对应名次。
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param score int整型一维数组 运动员成绩 # @return string字符串一维数组 # class Solution: def findRelativeRanks(self , score ): # write code here medal = ["Gold Medal", "Silver Medal", "Bronze Medal"] num = copy.deepcopy (score) num.sort(reverse = True) j = 4 for i in range(len(score)): if i < 3: score[score.index(num[i])] = medal[i] else: score[score.index(num[i])] = str(j) j += 1 return score不知道为什么明明可以通过,但在牛客网这里却通不过。重新做卷子想回看一下原题也做不到,😵