返回
用简单步骤理解相对名次问题:LeetCode 67
Android
2023-10-18 04:59:03
问题陈述
LeetCode 67:相对名次问题如下:
给定 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会分别获得金牌、银牌和铜牌。对于其余的所有运动员,只需给出他们的相对名次即可。
例如:
输入:
[5, 4, 3, 2, 1]
输出:
["金牌", "银牌", "铜牌", "第 4 名", "第 5 名"]
解题思路
要解决 LeetCode 67:相对名次问题,我们可以采用以下思路:
-
对给定的成绩进行排序 :首先,我们将给定的成绩列表进行排序,以便按从高到低的顺序排列。这将帮助我们轻松确定哪些运动员获得了前三名。
-
创建相对名次字典 :接下来,我们将创建一个相对名次字典。该字典将包含每个运动员的成绩作为键,以及他们的相对名次作为值。
-
遍历排序后的成绩列表 :然后,我们将遍历排序后的成绩列表。对于每个成绩,我们都会检查它是否在相对名次字典中。如果是,我们将使用字典中的值作为该成绩的相对名次。如果不是,我们将使用列表的索引作为相对名次。
-
为前三名分配奖牌 :最后,我们将为前三名的运动员分配奖牌。我们将金牌授予成绩最高者,银牌授予成绩第二高者,铜牌授予成绩第三高者。
代码实现
现在,我们来看看如何使用不同的编程语言实现此算法。
Python
def relative_ranks(scores):
"""
:type scores: List[int]
:rtype: List[str]
"""
# Sort the scores in descending order
sorted_scores = sorted(scores, reverse=True)
# Create a dictionary to store the relative ranks
relative_ranks = {}
# Assign medals to the top three athletes
medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
for i in range(3):
relative_ranks[sorted_scores[i]] = medals[i]
# Assign ranks to the remaining athletes
rank = 4
for score in scores:
if score not in relative_ranks:
relative_ranks[score] = "Rank {}".format(rank)
rank += 1
# Create the output list
output = []
for score in scores:
output.append(relative_ranks[score])
return output
# Example usage
scores = [5, 4, 3, 2, 1]
result = relative_ranks(scores)
print(result)
Java
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
/**
* Given a list of scores, find their relative ranks and return them in ascending order.
*
* @param scores the list of scores
* @return the list of relative ranks
*/
public List<String> relativeRanks(int[] scores) {
// Sort the scores in descending order
int[] sortedScores = Arrays.copyOf(scores, scores.length);
Arrays.sort(sortedScores);
// Create a map to store the relative ranks
Map<Integer, String> relativeRanks = new HashMap<>();
// Assign medals to the top three athletes
relativeRanks.put(sortedScores[0], "Gold Medal");
relativeRanks.put(sortedScores[1], "Silver Medal");
relativeRanks.put(sortedScores[2], "Bronze Medal");
// Assign ranks to the remaining athletes
int rank = 4;
for (int score : scores) {
if (!relativeRanks.containsKey(score)) {
relativeRanks.put(score, "Rank " + rank);
rank++;
}
}
// Create the output list
List<String> output = new ArrayList<>();
for (int score : scores) {
output.add(relativeRanks.get(score));
}
return output;
}
}
C++
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> relativeRanks(vector<int>& scores) {
// Sort the scores in descending order
vector<int> sortedScores = scores;
sort(sortedScores.begin(), sortedScores.end(), greater<int>());
// Create a map to store the relative ranks
map<int, string> relativeRanks;
// Assign medals to the top three athletes
relativeRanks[sortedScores[0]] = "Gold Medal";
relativeRanks[sortedScores[1]] = "Silver Medal";
relativeRanks[sortedScores[2]] = "Bronze Medal";
// Assign ranks to the remaining athletes
int rank = 4;
for (int score : scores) {
if (relativeRanks.find(score) == relativeRanks.end()) {
relativeRanks[score] = "Rank " + to_string(rank);
rank++;
}
}
// Create the output vector
vector<string> output;
for (int score : scores) {
output.push_back(relativeRanks[score]);
}
return output;
}
};
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution
{
public string[] RelativeRanks(int[] scores)
{
// Sort the scores in descending order
int[] sortedScores = (int[])scores.Clone();
Array.Sort(sortedScores);
Array.Reverse(sortedScores);
// Create a dictionary to store the relative ranks
Dictionary<int, string> relativeRanks = new Dictionary<int, string>();
// Assign medals to the top three athletes
relativeRanks.Add(sortedScores[0], "Gold Medal");
relativeRanks.Add(sortedScores[1], "Silver Medal");
relativeRanks.Add(sortedScores[2], "Bronze Medal");
// Assign ranks to the remaining athletes
int rank = 4;
foreach (int score in scores)
{
if (!relativeRanks.ContainsKey(score))
{
relativeRanks.Add(score, "Rank " + rank);
rank++;
}
}
// Create the output array
string[] output = new string[scores.Length];
for (int i = 0; i < scores.Length; i++)
{
output[i] = relativeRanks[scores[i]];
}
return output;
}
}
JavaScript
/**
* Given a list of scores, find their relative ranks and return them in ascending order.
*
* @param {number[]} scores the list of scores
* @return {string[]} the list of relative ranks
*/
const relativeRanks = (scores) => {
// Sort the scores in descending order
const sortedScores = [...scores].sort((a, b) => b - a);
// Create a map to store the relative ranks
const relativeRanks = {};
// Assign medals to the top three athletes
relativeRanks[sortedScores[0]] = "Gold Medal";
relativeRanks[sortedScores[1]] = "Silver Medal";
relativeRanks[sortedScores[2]] = "Bronze Medal";
// Assign ranks to the remaining athletes
let rank = 4;
for (let score of scores) {
if (!relativeRanks[score]) {
relativeRanks[score] = `Rank ${rank}`;
rank++;
}
}
// Create the output array
const output = [];
for (let score of scores) {
output.push(relativeRanks[score]);
}
return output;
};
总结
在本文中,我们详细介绍了如何解决 LeetCode 67:相对名