第十周leetcode题

xiaoxiao2021-02-28  56

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.

将给出的成绩从大到小排序,前三名分别获得金银铜牌,其他则输出位次。注意函数返回的是string类型的vector。用一个int数组复制vector里的数字,排序。再用另一个数组记下排序的结果。最后顺序检索原向量中的元素,输出它们对应的奖牌或位次。代码如下:

class Solution {         public:     vector<string> findRelativeRanks(vector<int>& nums) {                  int num[nums.size()];                  vector<string> a;         a.resize(nums.size());          for(int i=0;i<nums.size();i++)         {             num[i]=nums[i];         }         sort(num, num+nums.size(),greater<int>());         int ran[num[0]+1]={0};                  for(int i=0;i<nums.size();i++)         {             ran[num[i]]=i+1;         }                   for(int i=0;i<nums.size();i++)         {             if(ran[nums[i]]==1)a[i]="Gold Medal";             else if(ran[nums[i]]==2)a[i]="Silver Medal";             else if(ran[nums[i]]==3)a[i]="Bronze Medal";             else a[i]=to_string(ran[nums[i]]);         }                  return a;     } };

转载请注明原文地址: https://www.6miu.com/read-40463.html

最新回复(0)