LeetCode 题解工作台
颜色分类
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums , 原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 我们使用整数 0 、 1 和 2 分别表示红色、白色和蓝色。 必须在不使用库内置的 sort 函数的情况下解决这个问题。 示例 1: 输入: nums =…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们定义三个指针 , 和 ,其中指针 用于指向数组中元素值为 的最右边界,指针 用于指向数组中元素值为 的最左边界,初始时 , 。指针 用于指向当前遍历的元素,初始时 。 当 $k \lt j$ 时,我们执行如下操作:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
必须在不使用库内置的 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.length1 <= n <= 300nums[i]为0、1或2
进阶:
- 你能想出一个仅使用常数空间的一趟扫描算法吗?
解题思路
方法一:三指针
我们定义三个指针 , 和 ,其中指针 用于指向数组中元素值为 的最右边界,指针 用于指向数组中元素值为 的最左边界,初始时 , 。指针 用于指向当前遍历的元素,初始时 。
当 时,我们执行如下操作:
- 若 ,则将其与 交换,然后 和 都加 ;
- 若 ,则将其与 交换,然后 减 ;
- 若 ,则 加 。
遍历结束后,数组中的元素就被分成了 , 和 三个部分。
时间复杂度 ,其中 是数组的长度。只需要遍历一遍数组即可。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.