LeetCode 题解工作台

按奇偶排序数组 II

给定一个非负整数数组 nums , nums 中一半整数是 奇数 ,一半整数是 偶数 。 对数组进行排序,以便当 nums[i] 为奇数时, i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数 。 你可以返回 任何满足上述条件的数组作为答案 。 示例 1: 输入: nums = [4,…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们用两个指针 和 分别指向偶数下标和奇数下标,初始时 $i = 0$, $j = 1$。 当 指向偶数下标时,如果 是奇数,那么我们需要找到一个奇数下标 ,使得 是偶数,然后交换 和 。继续遍历,直到 指向数组末尾。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个非负整数数组 nums,  nums 中一半整数是 奇数 ,一半整数是 偶数

对数组进行排序,以便当 nums[i] 为奇数时,i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数

你可以返回 任何满足上述条件的数组作为答案

 

示例 1:

输入:nums = [4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。

示例 2:

输入:nums = [2,3]
输出:[2,3]

 

提示:

  • 2 <= nums.length <= 2 * 104
  • nums.length 是偶数
  • nums 中一半是偶数
  • 0 <= nums[i] <= 1000

 

进阶:可以不使用额外空间解决问题吗?

lightbulb

解题思路

方法一:双指针

我们用两个指针 iijj 分别指向偶数下标和奇数下标,初始时 i=0i = 0, j=1j = 1

ii 指向偶数下标时,如果 nums[i]\textit{nums}[i] 是奇数,那么我们需要找到一个奇数下标 jj,使得 nums[j]\textit{nums}[j] 是偶数,然后交换 nums[i]\textit{nums}[i]nums[j]\textit{nums}[j]。继续遍历,直到 ii 指向数组末尾。

时间复杂度 O(n)O(n),其中 nn 是数组 nums[i]\textit{nums}[i] 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
        n, j = len(nums), 1
        for i in range(0, n, 2):
            if nums[i] % 2:
                while nums[j] % 2:
                    j += 2
                nums[i], nums[j] = nums[j], nums[i]
        return nums
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for a candidate's understanding of two-pointer techniques and their ability to maintain invariant conditions during an array traversal.

  • question_mark

    Evaluate the candidate's familiarity with array manipulation and in-place swapping as an optimization technique.

  • question_mark

    Assess how the candidate balances time complexity and space constraints in their approach.

warning

常见陷阱

外企场景
  • error

    Failing to maintain the correct parity at each index by improperly swapping or missing swaps for some elements.

  • error

    Incorrect handling of boundary conditions, such as when pointers exceed array limits.

  • error

    Using additional space for sorting unnecessarily, violating the space complexity requirement of O(1).

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling cases with larger arrays where the time complexity becomes critical.

  • arrow_right_alt

    Handling edge cases with arrays where all elements are already sorted by parity.

  • arrow_right_alt

    Generalizing the two-pointer technique for arrays of odd length or arrays with other constraints.

help

常见问题

外企场景

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