Python 基礎知識簡單

根據另一個數組排序

「根據另一個陣列排序」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 sort_by_order(arr1, arr2),根據 arr2 定義的順序對 arr1 的元素進行排序。 arr1 中出現在 arr2 中的元素應按照它們在 arr2 中出現的順序排在前面。不在 arr2 中的元素應依排序(升序)順序出現在最後。

約束條件
  • 1 <= len(arr1) <= 10^5
  • 0 <= len(arr2) <= 100
  • Elements of arr2 are distinct

範例

Example 1
Input
arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8], arr2 = [2, 1, 8, 3]
Output
[2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]
Explanation

First all 2s, then 1s, then 8s, then 3s (order from arr2). Remaining [5,6,7,9] sorted ascending.

Example 2
Input
arr1 = [4, 5, 6], arr2 = [6, 4]
Output
[6, 4, 5]
Explanation

6 first, then 4 (per arr2 order). 5 is not in arr2, goes at end.

Example 3
Input
arr1 = [1, 2, 3], arr2 = []
Output
[1, 2, 3]
Explanation

No order specified, so sort ascending.

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

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