Python 基礎知識簡單

前半部升序排列,後半部降序排列

「前半部升序和後半部降序排序」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 sort_half(arr) ,它接受一個整數列表並傳回一個新列表,其中前半部按升序排序,後半部按降序排序。如果陣列長度為奇數,則中間元素屬於前半部。例如,對於長度 5,前 3 個元素按升序排序,後 2 個元素按降序排序。

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

範例

Example 1
Input
arr = [5, 2, 8, 1, 4, 7]
Output
[1, 2, 5, 8, 7, 4]
Explanation

First half [5,2,8] sorted ascending: [1,2,5]. Second half [1,4,7] sorted descending: [8,7,4]. Wait — we split the original array: first 3 elements [5,2,8] sort ascending -> [2,5,8], last 3 [1,4,7] sort descending -> [7,4,1]. Result: [2,5,8,7,4,1].

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

First half (3 elements) [3,1,2] sorted ascending: [1,2,3]. Second half (2 elements) [5,4] sorted descending: [5,4]. Result: [1,2,3,5,4].

Example 3
Input
arr = [9, 3, 6, 1]
Output
[3, 9, 6, 1]
Explanation

First half [9,3] ascending: [3,9]. Second half [6,1] descending: [6,1]. Result: [3,9,6,1].

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

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