zoukankan      html  css  js  c++  java
  • [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.
    Note:
    N is a positive integer and won't exceed 10,000.
    All the scores of athletes are guaranteed to be unique.

    思路:

    思路很朴素,首先就是排序,然后定义一个map,储存对应分数及其排名信息。最后再遍历一遍原来的分数数组,对应每一个分数

    给定相应的排名。注意,要提前备份原来的数组,因为排序之后数组顺序就变了。

    vector<string> findRelativeRanks(vector<int>& nums)
     {
         vector<int>backup = nums;
         vector<string>result;
         if(nums.size()==0)return result;
         sort(nums.begin(),nums.end(),greater<int>());
         map<int,string>table;
         char rank[10];
         for(int i = 0;i < nums.size();i++)
         {
             sprintf(rank,"%d",i+1);
             if(i == 0)table[nums[i]]="Gold Medal";
             else if(i == 1)table[nums[i]]="Silver Medal";
             else if(i == 2)table[nums[i]]="Bronze Medal";
             else  table[nums[i]] = rank;
         }
         result.push_back(table[backup[0]]);
         for(int i =1;i<nums.size();i++)
         {
                     result.push_back(table[backup[i]]);
         }
         return result;
    }
  • 相关阅读:
    算法训练 2的次幂表示
    算法训练 进制转换
    算法训练 Beaver's Calculator (蓝桥杯)
    抽签问题(不断优化)
    矩阵快速幂
    斐波那契数列
    找出最小自然数N,使N!在十进制下包含Q个0(输入Q,输出N)
    二维数组名是指针的指针吗?
    StringBuffer
    Lake Counting (POJ No.2386)
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6665157.html
Copyright © 2011-2022 走看看