LeetCode 题解工作台
根据给定数字划分数组
给你一个下标从 0 开始的整数数组 nums 和一个整数 pivot 。请你将 nums 重新排列,使得以下条件均成立: 所有小于 pivot 的元素都出现在所有大于 pivot 的元素 之前 。 所有等于 pivot 的元素都出现在小于和大于 pivot 的元素 中间 。 小于 pivot 的元素…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们可以遍历数组 ,按顺序找出所有小于 的元素,所有等于 的元素,以及所有大于 的元素,然后将它们按照题目要求的顺序拼接起来。 时间复杂度 ,其中 为数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个整数 pivot 。请你将 nums 重新排列,使得以下条件均成立:
- 所有小于
pivot的元素都出现在所有大于pivot的元素 之前 。 - 所有等于
pivot的元素都出现在小于和大于pivot的元素 中间 。 - 小于
pivot的元素之间和大于pivot的元素之间的 相对顺序 不发生改变。- 更正式的,考虑每一对
pi,pj,pi是初始时位置i元素的新位置,pj是初始时位置j元素的新位置。如果i < j且两个元素 都 小于(或大于)pivot,那么pi < pj。
- 更正式的,考虑每一对
请你返回重新排列 nums 数组后的结果数组。
示例 1:
输入:nums = [9,12,5,10,14,3,10], pivot = 10 输出:[9,5,3,10,10,12,14] 解释: 元素 9 ,5 和 3 小于 pivot ,所以它们在数组的最左边。 元素 12 和 14 大于 pivot ,所以它们在数组的最右边。 小于 pivot 的元素的相对位置和大于 pivot 的元素的相对位置分别为 [9, 5, 3] 和 [12, 14] ,它们在结果数组中的相对顺序需要保留。
示例 2:
输入:nums = [-3,4,3,2], pivot = 2 输出:[-3,2,4,3] 解释: 元素 -3 小于 pivot ,所以在数组的最左边。 元素 4 和 3 大于 pivot ,所以它们在数组的最右边。 小于 pivot 的元素的相对位置和大于 pivot 的元素的相对位置分别为 [-3] 和 [4, 3] ,它们在结果数组中的相对顺序需要保留。
提示:
1 <= nums.length <= 105-106 <= nums[i] <= 106pivot等于nums中的一个元素。
解题思路
方法一:模拟
我们可以遍历数组 ,按顺序找出所有小于 的元素,所有等于 的元素,以及所有大于 的元素,然后将它们按照题目要求的顺序拼接起来。
时间复杂度 ,其中 为数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
a, b, c = [], [], []
for x in nums:
if x < pivot:
a.append(x)
elif x == pivot:
b.append(x)
else:
c.append(x)
return a + b + c
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) since each element is visited once. Space complexity is O(N) for storing elements in three separate lists before merging. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Do you track elements less than, equal to, and greater than the pivot separately?
- question_mark
Can you maintain the original relative ordering of elements in a single pass?
- question_mark
Are you considering both time efficiency and space trade-offs for this two-pointer pattern?
常见陷阱
外企场景- error
Trying to do in-place swaps without tracking order, which breaks relative ordering.
- error
Confusing elements equal to the pivot with either smaller or larger group.
- error
Using nested loops, increasing time complexity unnecessarily.
进阶变体
外企场景- arrow_right_alt
Partition using in-place stable partition algorithms to reduce space but maintain order.
- arrow_right_alt
Extend to multiple pivots, sorting by multiple thresholds with stable grouping.
- arrow_right_alt
Apply to linked lists instead of arrays to practice pointer manipulation.