竞争性编程简单

波浪排序

“波排序”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 wave_sort(arr),它接受整数数组 arr,按升序对其进行排序,然后交换从索引 0 开始的每对相邻元素(即交换 arr[0] 和 arr[1],然后交换 arr[2] 和 arr[3],依此类推)以生成满足属性 arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]... 的波排序数组。返回结果数组。

约束条件
  • 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 资源

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