Python 基础知识简单

按排名替换每个元素

“按等级替换每个元素”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 replace_by_rank(arr) ,当数组按升序排序时,该函数将数组中的每个元素替换为其排名。最小的元素排名 1,第二小的元素排名 2,依此类推。如果两个元素相等,它们将获得相同的排名。返回排名数组。

约束条件
  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9

示例

Example 1
Input
arr = [20, 15, 26, 2, 98, 6]
Output
[4, 3, 5, 1, 6, 2]
Explanation

Sorted: [2,6,15,20,26,98]. Ranks: 2->1, 6->2, 15->3, 20->4, 26->5, 98->6.

Example 2
Input
arr = [10, 10, 10]
Output
[1, 1, 1]
Explanation

All elements are equal, so all get rank 1.

Example 3
Input
arr = [5, 3, 1]
Output
[3, 2, 1]
Explanation

Sorted: [1,3,5]. Ranks: 1->1, 3->2, 5->3.

Need a Hint?
考虑使用特定于数组的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。