LeetCode 题解工作台

颜色分类

给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums , 原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 我们使用整数 0 、 1 和 2 分别表示红色、白色和蓝色。 必须在不使用库内置的 sort 函数的情况下解决这个问题。 示例 1: 输入: nums =…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 双·指针·invariant

bolt

答案摘要

我们定义三个指针 , 和 ,其中指针 用于指向数组中元素值为 的最右边界,指针 用于指向数组中元素值为 的最左边界,初始时 , 。指针 用于指向当前遍历的元素,初始时 。 当 $k \lt j$ 时,我们执行如下操作:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

我们使用整数 0、 12 分别表示红色、白色和蓝色。

必须在不使用库内置的 sort 函数的情况下解决这个问题。

 

示例 1:

输入:nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]

示例 2:

输入:nums = [2,0,1]
输出:[0,1,2]

 

提示:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i]012

 

进阶:

  • 你能想出一个仅使用常数空间的一趟扫描算法吗?
lightbulb

解题思路

方法一:三指针

我们定义三个指针 ii, jjkk,其中指针 ii 用于指向数组中元素值为 00 的最右边界,指针 jj 用于指向数组中元素值为 22 的最左边界,初始时 i=1i=-1, j=nj=n。指针 kk 用于指向当前遍历的元素,初始时 k=0k=0

k<jk \lt j 时,我们执行如下操作:

  • nums[k]=0nums[k]=0,则将其与 nums[i+1]nums[i+1] 交换,然后 iikk 都加 11
  • nums[k]=2nums[k]=2,则将其与 nums[j1]nums[j-1] 交换,然后 jj11
  • nums[k]=1nums[k]=1,则 kk11

遍历结束后,数组中的元素就被分成了 [0,i][0,i], [i+1,j1][i+1,j-1][j,n1][j,n-1] 三个部分。

时间复杂度 O(n)O(n),其中 nn 是数组的长度。只需要遍历一遍数组即可。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        i, j, k = -1, len(nums), 0
        while k < j:
            if nums[k] == 0:
                i += 1
                nums[i], nums[k] = nums[k], nums[i]
                k += 1
            elif nums[k] == 2:
                j -= 1
                nums[j], nums[k] = nums[k], nums[j]
            else:
                k += 1
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Do you correctly maintain the low, mid, and high pointers to enforce the invariant?

  • question_mark

    Can you handle arrays where all elements are the same or already partially sorted?

  • question_mark

    Will you update indices carefully after each swap to avoid overwriting unsorted values?

warning

常见陷阱

外企场景
  • error

    Swapping a 0 or 2 without updating the current index can skip elements or cause infinite loops.

  • error

    Failing to maintain the invariant partitions correctly can mix colors and require multiple passes.

  • error

    Edge cases like single-element arrays or arrays with only one color may break naive implementations if not handled.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Sort Colors II: Extend the problem to k colors represented by integers 0 to k-1, still requiring in-place ordering.

  • arrow_right_alt

    Dutch National Flag Variant: Separate an array into three partitions based on a pivot value, testing invariant tracking under different rules.

  • arrow_right_alt

    Sort Colors with Stability: Sort the array while preserving the relative order of 1s to test the effect on two-pointer swaps.

help

常见问题

外企场景

颜色分类题解:双·指针·invariant | LeetCode #75 中等