算法题 |
---|
算法题 |
---|
给出 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”(“Gold Medal”, “Silver Medal”, “Bronze Medal”)。
(注:分数越高的选手,排名越靠前。)
示例1:
输入: [5, 4, 3, 2, 1]
输出: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” ("Gold Medal", "Silver Medal" and "Bronze Medal").
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
提示:
先保存原本的索引,再排序
代码:
public class Solution {
class Pair {
public int idx;
public int rank;
}
string[] medalStr = { "", "Gold Medal", "Silver Medal", "Bronze Medal" };
string GetRankStr(int rank) {
if (rank > 3) return rank.ToString();
else return medalStr[rank];
}
public string[] FindRelativeRanks(int[] nums) {
int n = nums.Length;
Pair[] ps = new Pair[n];
for (int i = 0; i < n; ++i)
ps[i] = new Pair() { idx = i, rank = nums[i] };
Array.Sort(ps, (a, b) => b.rank - a.rank);
string[] ans = new string[n];
for (int rank = 0; rank < n; )
ans[ps[rank].idx] = GetRankStr(++rank);
return ans;
}
}
执行结果
通过
执行用时:88 ms,在所有 Java 提交中击败了22.50%的用户
内存消耗:36.4 MB,在所有 Java 提交中击败了12.50%的用户
思路解析 先排序,使用哈希求解
代码:
class Solution {
public String[] findRelativeRanks(int[] score) {
int len = score.length;
String[] rank = new String[len];
// 先排一下序
int[] x = score.clone();
Arrays.sort(score);
// System.out.println(Arrays.toString(score));
// hash记录 排名
HashMap<Integer, String> map = new HashMap<>();
if (len > 3) {
for (int i = len - 4; i >= 0; --i) {
map.put(score[i], len - i + "");
}
map.put(score[len-1], "Gold Medal");
map.put(score[len-2], "Silver Medal");
map.put(score[len-3], "Bronze Medal");
} else {
if( len == 1) {
map.put(score[0], "Gold Medal");
} else if ( len == 2) {
map.put(score[0], "Silver Medal");
map.put(score[1], "Gold Medal");
} else {
map.put(score[0], "Bronze Medal");
map.put(score[1], "Silver Medal");
map.put(score[2], "Gold Medal");
}
}
for (int i = 0; i < len; i++) {
rank[i] = map.get(x[i]);
}
return rank;
}
}
执行结果
通过
执行用时:11 ms,在所有 Java 提交中击败了48.26%的用户
内存消耗:39.2 MB,在所有 Java 提交中击败了78.05%的用户