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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。