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] 也会被…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们用两个指针 和 分别指向数组的首尾,当 $i < j$ 时,执行以下操作。 - 如果 为偶数,则 自增 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 5000
  • 0 <= nums[i] <= 5000
lightbulb

解题思路

方法一:双指针

我们用两个指针 iijj 分别指向数组的首尾,当 i<ji < j 时,执行以下操作。

  • 如果 nums[i]nums[i] 为偶数,则 ii 自增 11
  • 如果 nums[j]nums[j] 为奇数,则 jj 自减 11
  • 如果 nums[i]nums[i] 为奇数,且 nums[j]nums[j] 为偶数,则交换 nums[i]nums[i]nums[j]nums[j]。然后 ii 自增 11,而 jj 自减 11

最后返回数组 numsnums 即可。

时间复杂度 O(n)O(n),其中 nn 是数组 numsnums 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

按奇偶排序数组题解:双·指针·invariant | LeetCode #905 简单