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

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。