# 0324. 摆动排序 II

### 题目地址(324. 摆动排序 II)

<https://leetcode.cn/problems/wiggle-sort-ii/>

### 题目描述

```
给你一个整数数组 nums，将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]... 的顺序。

你可以假设所有输入数组都可以得到满足题目要求的结果。

 

示例 1：

输入：nums = [1,5,1,1,6,4]
输出：[1,6,1,5,1,4]
解释：[1,4,1,5,1,6] 同样是符合题目要求的结果，可以被判题程序接受。


示例 2：

输入：nums = [1,3,2,2,3,1]
输出：[2,3,1,3,1,2]


 

提示：

1 <= nums.length <= 5 * 104
0 <= nums[i] <= 5000
题目数据保证，对于给定的输入 nums ，总能产生满足题目要求的结果

 

进阶：你能用 O(n) 时间复杂度和 / 或原地 O(1) 额外空间来实现吗？
```

### 前置知识

*

### 公司

* 暂无

### 思路

这是一道构造题目，一般来说构造题目的难度都偏大一点，这一道题目也不例外，尤其是进阶。关于进阶不在这里展开，因为[题解区](https://leetcode.cn/problems/wiggle-sort-ii/solution/)给出了很多优秀的解法了。

这道题让我们重新排 nums， 使得奇数索引的数都比相邻的偶数索引大。

我们可以先进行一次倒序排序。接下来先从小到大给奇数索引放置数字，然后再次从小到大给偶数索引放置数字即可。

> 这里的从小到大指的是索引值从小到大，即先放索引较小的，再放索引较大的。

为什么可行？

因为我们是倒序排序的，因此后放置的偶数索引一定是不大于奇数索引的。但是能够保证严格小于相邻的奇数索引么？

由于题目保证了有解。因此实际上按照这种放置方法可以，但是如果：先从小到大给奇数索引放置数字，然后再次从大到小给偶数索引放置数字。那么就有可能无解。无解的情况是数组中有大量的相同数字。但是题目保证有解的情况，**先从小到大给奇数索引放置数字，然后再次从小到大给偶数索引放置数字** 是不会有问题的。

### 关键点

* 排序后按照奇偶性分别放置

### 代码

* 语言支持：Python3

Python3 Code:

```python

class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        s = sorted(nums, reverse=True)

        i = 1
        j = 0
        while i < n:
            nums[i] = s[j]
            i += 2
            j += 1
        i = 0
        while i < n:
            nums[i] = s[j]
            i += 2
            j += 1

```

**复杂度分析**

令 n 为数组长度。

* 时间复杂度：$O(nlogn)$ 主要是排序
* 空间复杂度：$O(n)$ 拷贝了一个新的数组 s

> 此题解由 [力扣刷题插件](https://leetcode-pp.github.io/leetcode-cheat/?tab=solution-template) 自动生成。

力扣的小伙伴可以[关注我](https://leetcode-cn.com/u/fe-lucifer/)，这样就会第一时间收到我的动态啦\~

以上就是本文的全部内容了。大家对此有何看法，欢迎给我留言，我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库：<https://github.com/azl397985856/leetcode> 。 目前已经 40K star 啦。大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。

关注公众号力扣加加，努力用清晰直白的语言还原解题思路，并且有大量图解，手把手教你识别套路，高效刷题。

![](https://p.ipic.vip/vwyqn5.jpg)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leetcode-solution-leetcode-pp.gitbook.io/leetcode-solution/medium/324.wiggle-sort-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
