Leetcode 0922. Sort Array By Parity II
922. Sort Array By Parity II
Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this condition.
Example 1:
1 | Input: nums = [4,2,5,7] |
Example 2:
1 | Input: nums = [2,3] |
双指针解法:
- 初始化:
- 偶数索引指针
i从 0 开始,每次移动 2 步 - 奇数索引指针
j从 1 开始,每次移动 2 步
- 偶数索引指针
- 遍历与交换:
- 当偶数索引
i上的元素是奇数时 - 移动奇数索引指针
j找到一个偶数 - 交换这两个元素,使它们都处于正确的位置
- 当偶数索引
- 终止条件:
- 当
i遍历完所有偶数索引(i < n),数组已满足条件
- 当
复杂度分析
- 时间复杂度:O (n),其中 n 是数组长度。每个元素最多被访问一次
- 空间复杂度:O (1),只使用了两个指针变量,原地操作
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

