Skip to content

Commit aaacc37

Browse files
committed
506. 相对名次
1 parent 7b3f233 commit aaacc37

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@
9898
|485|[最大连续 1 的个数](https://leetcode.cn/problems/max-consecutive-ones/)|[JavaScript](./algorithms/max-consecutive-ones.js)|Easy|
9999
|495|[提莫攻击](https://leetcode.cn/problems/teemo-attacking/)|[JavaScript](./algorithms/teemo-attacking.js)|Easy|
100100
|498|[对角线遍历](https://leetcode.cn/problems/diagonal-traverse/)|[JavaScript](./algorithms/diagonal-traverse.js)|Medium|
101+
|506|[相对名次](https://leetcode.cn/problems/relative-ranks/)|[JavaScript](./algorithms/relative-ranks.js)|Easy|
101102
|509|[斐波那契数](https://leetcode.cn/problems/fibonacci-number/)|[JavaScript](./algorithms/fibonacci-number.js)|Easy|
102103
|515|[在每个树行中找最大值](https://leetcode.cn/problems/find-largest-value-in-each-tree-row/)|[JavaScript](./algorithms/find-largest-value-in-each-tree-row.js)|Medium|
103104
|520|[检测大写字母](https://leetcode.cn/problems/detect-capital/)|[JavaScript](./algorithms/detect-capital.js)|Easy|

algorithms/relative-ranks.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {number[]} score
3+
* @return {string[]}
4+
*/
5+
var findRelativeRanks = function (score) {
6+
// 对得分从高到低进行排序
7+
const top = score.slice().sort((a, b) => b - a);
8+
const result = [];
9+
const o = {};
10+
11+
// 哈希表 保存 score[i] 的原始索引
12+
for (let i = 0; i < score.length; i++) {
13+
o[score[i]] = i;
14+
}
15+
for (let i = 0; i < top.length; i++) {
16+
// 原始索引
17+
const originalIndex = o[top[i]];
18+
// 排名
19+
let rank = i + 1;
20+
if (rank === 1) {
21+
answer = "Gold Medal";
22+
} else if (rank === 2) {
23+
answer = "Silver Medal";
24+
} else if (rank === 3) {
25+
answer = "Bronze Medal";
26+
} else {
27+
answer = rank.toString();
28+
}
29+
result[originalIndex] = answer;
30+
}
31+
32+
return result;
33+
};

0 commit comments

Comments
 (0)