LeetCode 题解工作台
重新放置石块
给你一个下标从 0 开始的整数数组 nums ,表示一些石块的初始位置。再给你两个长度 相等 下标从 0 开始的整数数组 moveFrom 和 moveTo 。 在 moveFrom.length 次操作内,你将改变石块的位置。在第 i 次操作中,你将位置在 moveFrom[i] 的所有石块移到位…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 记录所有有石块的位置,初始时 中包含 中的所有元素。然后我们遍历 和 ,每次将 从 中移除,再将 添加到 中。最后我们将 中的元素排序后返回即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 是数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,表示一些石块的初始位置。再给你两个长度 相等 下标从 0 开始的整数数组 moveFrom 和 moveTo 。
在 moveFrom.length 次操作内,你将改变石块的位置。在第 i 次操作中,你将位置在 moveFrom[i] 的所有石块移到位置 moveTo[i] 。
完成这些操作后,请你按升序返回所有 有 石块的位置。
注意:
- 如果一个位置至少有一个石块,我们称这个位置 有 石块。
- 一个位置可能会有多个石块。
示例 1:
输入:nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5] 输出:[5,6,8,9] 解释:一开始,石块在位置 1,6,7,8 。 第 i = 0 步操作中,我们将位置 1 处的石块移到位置 2 处,位置 2,6,7,8 有石块。 第 i = 1 步操作中,我们将位置 7 处的石块移到位置 9 处,位置 2,6,8,9 有石块。 第 i = 2 步操作中,我们将位置 2 处的石块移到位置 5 处,位置 5,6,8,9 有石块。 最后,至少有一个石块的位置为 [5,6,8,9] 。
示例 2:
输入:nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2] 输出:[2] 解释:一开始,石块在位置 [1,1,3,3] 。 第 i = 0 步操作中,我们将位置 1 处的石块移到位置 2 处,有石块的位置为 [2,2,3,3] 。 第 i = 1 步操作中,我们将位置 3 处的石块移到位置 2 处,有石块的位置为 [2,2,2,2] 。 由于 2 是唯一有石块的位置,我们返回 [2] 。
提示:
1 <= nums.length <= 1051 <= moveFrom.length <= 105moveFrom.length == moveTo.length1 <= nums[i], moveFrom[i], moveTo[i] <= 109- 测试数据保证在进行第
i步操作时,moveFrom[i]处至少有一个石块。
解题思路
方法一:哈希表
我们用一个哈希表 记录所有有石块的位置,初始时 中包含 中的所有元素。然后我们遍历 和 ,每次将 从 中移除,再将 添加到 中。最后我们将 中的元素排序后返回即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def relocateMarbles(
self, nums: List[int], moveFrom: List[int], moveTo: List[int]
) -> List[int]:
pos = set(nums)
for f, t in zip(moveFrom, moveTo):
pos.remove(f)
pos.add(t)
return sorted(pos)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently handle updates to the positions of multiple marbles in each move?
- question_mark
Does the candidate consider using a set or hash map to manage the unique positions of marbles?
- question_mark
Is the candidate able to optimize the sorting step to avoid unnecessary computation?
常见陷阱
外企场景- error
Failing to account for the possibility of multiple marbles being moved to the same position.
- error
Not using efficient data structures like sets to handle unique positions and optimize the move process.
- error
Overcomplicating the sorting step or failing to sort the final result efficiently.
进阶变体
外企场景- arrow_right_alt
Handle a case where `nums`, `moveFrom`, and `moveTo` have large sizes and test for performance.
- arrow_right_alt
Consider scenarios where marbles can move from a position to the same position multiple times, ensuring no unnecessary changes are made.
- arrow_right_alt
Explore different ways of sorting the final list, such as using a priority queue or quicksort for optimization.