⚡Flashcard Drill➔
NeetCode #122LC-280MediumArrays & HashingNC Algo100
← Back to All Problems

#122 · #280 · Wiggle Sort(摆动排序)

📌 Problem Statement & Constraints

Given an unsorted array nums, reorder it in place so that nums[0] <= nums[1] >= nums[2] <= nums[3] >= .... Constraints: 1 <= nums.length <= 5 * 10^4, 0 <= nums[i] <= 10^4.

💡 Core Algorithmic Approaches

  1. Only adjacent pairs are constrained, so a single left-to-right pass with local swaps suffices.
  2. At an even index i we need nums[i] <= nums[i+1]; at an odd index i we need nums[i] >= nums[i+1].
  3. If the required relation is violated, swap nums[i] and nums[i+1]. Each swap fixes the pair and cannot break an earlier pair, because a swap only ever moves a smaller value left or a larger value right in a way that preserves the earlier inequality.
  4. This is O(n) time with O(1) space, beating the sort-then-interleave approach which is O(n log n).

💻 Benchmark Python3 Implementation

class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        for i in range(len(nums) - 1):
            if i % 2 == 0:
                if nums[i] > nums[i + 1]:        # need nums[i] <= nums[i+1]
                    nums[i], nums[i + 1] = nums[i + 1], nums[i]
            else:
                if nums[i] < nums[i + 1]:        # need nums[i] >= nums[i+1]
                    nums[i], nums[i + 1] = nums[i + 1], nums[i]


# Sort-then-interleave: O(n log n), simpler to argue about correctness
class Solution2:
    def wiggleSort(self, nums: List[int]) -> None:
        nums.sort()
        for i in range(1, len(nums) - 1, 2):
            nums[i], nums[i + 1] = nums[i + 1], nums[i]

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) for the single-pass swap version; O(n log n) for the sort-based version.
💾 Space Complexity
O(1) for the swap version; O(1) extra for the sort version (in-place sort) but O(n log n) time.

⚠️ Interview Pitfalls & Follow-ups

  • Sorting and then reversing every other pair incorrectly: the interleave must swap (i, i+1) for odd i starting at 1, as shown.
  • Trying to satisfy both neighbours at once with a median partition: that is the approach for the harder variant (Wiggle Sort II), not this one.
  • Using <= and >= loosely: the statement uses non-strict inequalities, so equal neighbours are allowed; do not add extra swaps.
  • Returning the array: the signature returns None; the reordering must be in place.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

摆动排序

给你一个整数数组 nums,将它重新排列成摆动序列。摆动序列满足 nums[0] &lt;= nums[1] &gt;= nums[2] &lt;= nums[3] &gt;= ... 。答案可能不唯一,返回任意一个满足条件的排列即可。请 原地 完成。约束:1 ≤ nums.length ≤ 5 × 10^4;0 ≤ nums[i] ≤ 10^4。

核心要点

  • 排序后交换相邻对 :先排序,再把 (1,2)、(3,4)、(5,6)… 这些相邻对交换位置。时间 O(n log n)。
  • 一次遍历贪心交换(更优) :从左到右扫描,对每个位置 i,根据 i 的奇偶性决定比较方向:奇数下标要求 nums[i] &gt;= nums[i-1] ,偶数下标要求 nums[i] &lt;= nums[i-1] ;不满足就交换这两个元素。
  • 为什么一次遍历就够 :交换 nums[i-1] 与 nums[i] 只会影响这两个位置,且交换后位置 i-1 与 i-2 的关系仍然成立(因为新值恰好落在两者之间),因此不需要回溯。
  • 奇偶性记忆口诀 : i 为奇数时把大的换到 i, i 为偶数时把小的换到 i。

常见陷阱

  • 奇偶性判断写反 :奇数下标 i 要求 nums[i] &gt;= nums[i-1] (把大的放右边),偶数下标要求 nums[i] &lt;= nums[i-1] 。写反会得到 &gt;= 与 &lt;= 颠倒的序列。
  • 以为需要排序 :排序解法正确但为 O(n log n),本题存在 O(n) 的贪心解,面试中应优先给出。
  • 与 324 摆动排序 II 混淆 :324 要求 nums[0] &lt; nums[1] &gt; nums[2] &lt; ... ( 严格 不等),且必须处理重复元素的「等值相邻」问题,难度高得多(需三分 + 交叉填充)。本题只要求非严格不等。
  • 忘记本题允许重复元素 : &lt;= 与 &gt;= 是非严格比较,相等元素相邻是合法的,无需额外处理。

参考实现

class Solution:
    def wiggleSort(self, nums: list[int]) -> None:
        """原地摆动排序,O(n) 时间。"""
        for i in range(1, len(nums)):
            if i % 2 == 1:
                # 奇数下标:要求 nums[i] >= nums[i-1]
                if nums[i] < nums[i - 1]:
                    nums[i], nums[i - 1] = nums[i - 1], nums[i]
            else:
                # 偶数下标:要求 nums[i] <= nums[i-1]
                if nums[i] > nums[i - 1]:
                    nums[i], nums[i - 1] = nums[i - 1], nums[i]