競賽程式設計簡單

波浪排序

“波排序”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 wave_sort(arr),它接受整數數組 arr,按升序對其進行排序,然後交換從索引 0 開始的每對相鄰元素(即交換 arr[0] 和 arr[1],然後交換 arr[2] 和 arr[3],依此類推)以產生滿足屬性__ 的數組。傳回結果數組。

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

範例

Example 1
Input
wave_sort([3, 6, 5, 10, 7, 20])
Output
[5, 3, 7, 6, 20, 10]
Explanation

First, sort the array to get [3, 5, 6, 7, 10, 20]. Swapping adjacent pairs: swap 3 and 5 -> [5, 3...], swap 6 and 7 -> [..., 7, 6...], swap 10 and 20 -> [..., 20, 10]. Result is [5, 3, 7, 6, 20, 10].

Example 2
Input
wave_sort([10, 90, 49, 2, 1, 5, 23])
Output
[2, 1, 10, 5, 49, 23, 90]
Explanation

Sort array to [1, 2, 5, 10, 23, 49, 90]. Swapping adjacent pairs gives [2, 1, 10, 5, 49, 23, 90].

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

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