zoukankan      html  css  js  c++  java
  • [LeetCode] 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:

    1. N is a positive integer and won't exceed 10,000.
    2. All the scores of athletes are guaranteed to be unique.

    使用一个临时数组存储原数组按逆序排序后的元素,遍历临时数组,找出临时数组中元素在原数组中的位置。然后根据该位置在结果字符串数组中添加排名信息。效率不是很高,但是还是成功AC。

    class Solution {
    public:
        vector<string> findRelativeRanks(vector<int>& nums) {
            vector<string> res(nums.size(), "");
            vector<int> tmp(nums.begin(), nums.end());
            sort(tmp.begin(), tmp.end(), [](int a, int b) { return a > b; });
            for (int i = 0; i != tmp.size(); i++) {
                for (int j = 0; j != nums.size(); j++) {
                    if (nums[j] == tmp[i]) {
                        if (i == 0)
                            res[j] = "Gold Medal";
                        else if (i == 1)
                            res[j] = "Silver Medal";
                        else if (i == 2)
                            res[j] = "Bronze Medal";
                        else
                            res[j] = to_string(i + 1);
                    }
                }
            }
            return res;
        }
    };
    // 209 ms
  • 相关阅读:
    C# 动态创建SQL数据库(一)
    在Winform中菜单动态添加“最近使用文件”
    转(C# 类似右键菜单弹出窗体)
    为什么不能用Abort退出线程
    C# GDI绘制波形图
    转(C# 实现生产者消费者队列)
    为字段设置初始值
    闲话资源管理
    正确使用 new 修饰符
    减少装箱与拆箱
  • 原文地址:https://www.cnblogs.com/immjc/p/7190698.html
Copyright © 2011-2022 走看看