LeetCode 题解工作台
按奇偶排序数组
给你一个整数数组 nums ,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。 返回满足此条件的 任一数组 作为答案。 示例 1: 输入: nums = [3,1,2,4] 输出: [2,4,3,1] 解释: [4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们用两个指针 和 分别指向数组的首尾,当 $i < j$ 时,执行以下操作。 - 如果 为偶数,则 自增 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。
返回满足此条件的 任一数组 作为答案。
示例 1:
输入:nums = [3,1,2,4] 输出:[2,4,3,1] 解释:[4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被视作正确答案。
示例 2:
输入:nums = [0] 输出:[0]
提示:
1 <= nums.length <= 50000 <= nums[i] <= 5000
解题思路
方法一:双指针
我们用两个指针 和 分别指向数组的首尾,当 时,执行以下操作。
- 如果 为偶数,则 自增 。
- 如果 为奇数,则 自减 。
- 如果 为奇数,且 为偶数,则交换 和 。然后 自增 ,而 自减 。
最后返回数组 即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
i, j = 0, len(nums) - 1
while i < j:
if nums[i] % 2 == 0:
i += 1
elif nums[j] % 2 == 1:
j -= 1
else:
nums[i], nums[j] = nums[j], nums[i]
i, j = i + 1, j - 1
return nums
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for candidate solutions using two pointers and minimal swaps.
- question_mark
Ask about maintaining invariants to ensure no even numbers are lost in placement.
- question_mark
Probe edge cases like arrays with all even or all odd numbers.
常见陷阱
外企场景- error
Swapping incorrectly when both pointers point to even numbers, causing unnecessary operations.
- error
Forgetting to increment the left pointer after a successful swap, breaking the invariant.
- error
Assuming stability is required when any valid ordering suffices, leading to extra complexity.
进阶变体
外企场景- arrow_right_alt
Sort array by parity while preserving original relative order of even and odd numbers (stable version).
- arrow_right_alt
Move all multiples of k to the front while keeping the rest in any order, generalizing the parity pattern.
- arrow_right_alt
Sort array into multiple partitions based on modulo classes instead of just even/odd separation.