競賽程式設計中等

按字典順序最小的數組

“字典最小數組”問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 lexicographically_smallest(arr, k) ,傳回依字典順序排列的最小數組,該數組可以透過最多交換相鄰元素 k 次來獲得。 arr 中的元素是唯一的。

約束條件
  • 1 <= len(arr) <= 1000
  • 0 <= k <= 10^5
  • -10^9 <= arr[i] <= 10^9

範例

Example 1
Input
lexicographically_smallest([7, 6, 9, 2, 1], 3)
Output
[2, 7, 6, 9, 1]
Explanation

To get the smallest possible element 2 to the front, we swap 9 and 2, then 6 and 2, then 7 and 2. This takes exactly 3 swaps, resulting in [2, 7, 6, 9, 1].

Example 2
Input
lexicographically_smallest([2, 1, 3], 1)
Output
[1, 2, 3]
Explanation

Swap 2 and 1 (1 swap) to get [1, 2, 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 資源

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