LeetCode 506. Relative Ranks

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.
class Solution {
public:
    static bool cmp(int a,int b){
        return a>b;
    }
    vector<string> findRelativeRanks(vector<int>& nums) {
          vector<string> res;
          map<int, int> rank;
          vector<int> temp;
          temp=nums;
          sort(nums.begin(),nums.end(),cmp);
          for(int i=0; i<nums.size(); i++)
              rank[nums[i]]=i+1;
          for(int i=0; i<temp.size(); i++)
              if(rank[temp[i]]==1)
                 res.push_back("Gold Medal");
              else if(rank[temp[i]]==2)
                 res.push_back("Silver Medal");
              else if(rank[temp[i]]==3)
                 res.push_back("Bronze Medal");
              else 
                 res.push_back(to_string(rank[temp[i]]));
        return res;
    }
};
posted @ 2018-12-05 22:14  A-Little-Nut  阅读(90)  评论(0编辑  收藏  举报