(算法分析Week13)Relative Ranks[Easy]

本文介绍了一种算法,用于解决根据运动员的成绩确定其相对排名,并为前三名分配金牌、银牌和铜牌的问题。该算法使用优先队列进行高效排序,并保持了输入顺序与输出排名的一致性。

506. Relative Ranks[Easy]

题目来源

Description

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.

Solution

一开始没理解题目,直接一个排序然后按顺序名次123,发现WA。然后看测例,发现是按照输入顺序对应输出相应的名次。C++可以直接用优先队列排序,用一对数存对应的分数和出现的位置,即make_pair(nums[i],i)
每次取优先队列的第一个,赋值当前名次,加入返回的vector即可。

Complexity analysis

O(n)

Code

class Solution {
public:
    string trans(int x) {
    ostringstream stream;
    stream<<x; 
    return stream.str();
    }
    vector<string> findRelativeRanks(vector<int>& nums) {
        priority_queue<pair<int, int>> que;
        for (int i = 0; i < nums.size(); i++) {
            que.push(make_pair(nums[i],i));
        }
        vector<string> result(nums.size(), "");  //记得初始化
        int count = 1;
        for (int i = 0; i < nums.size(); i++) {
            if (count == 1) {
                result[que.top().second] = "Gold Medal";
                count++;
            } else if (count == 2) {
                result[que.top().second] = "Silver Medal";
                count++;
            } else if (count == 3) {
                result[que.top().second] = "Bronze Medal";
                count++;
            } else {
                result[que.top().second] = trans(count);
                count++;
            }
            que.pop();
        }


        return result;
    }
};



Result

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值