LeetCode 题解工作台
替换数组中的元素
给你一个下标从 0 开始的数组 nums ,它包含 n 个 互不相同 的正整数。请你对这个数组执行 m 个操作,在第 i 个操作中,你需要将数字 operations[i][0] 替换成 operations[i][1] 。 题目保证在第 i 个操作中: operations[i][0] 在 num…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们先用哈希表 记录数组 中每个数字的下标,然后遍历操作数组 ,对于每个操作 $[x, y]$,我们将 在 中的下标 对应的数字替换为 ,并更新 中 的下标为 。 最后返回 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的数组 nums ,它包含 n 个 互不相同 的正整数。请你对这个数组执行 m 个操作,在第 i 个操作中,你需要将数字 operations[i][0] 替换成 operations[i][1] 。
题目保证在第 i 个操作中:
operations[i][0]在nums中存在。operations[i][1]在nums中不存在。
请你返回执行完所有操作后的数组。
示例 1:
输入:nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]] 输出:[3,2,7,1] 解释:我们对 nums 执行以下操作: - 将数字 1 替换为 3 。nums 变为 [3,2,4,6] 。 - 将数字 4 替换为 7 。nums 变为 [3,2,7,6] 。 - 将数字 6 替换为 1 。nums 变为 [3,2,7,1] 。 返回最终数组 [3,2,7,1] 。
示例 2:
输入:nums = [1,2], operations = [[1,3],[2,1],[3,2]] 输出:[2,1] 解释:我们对 nums 执行以下操作: - 将数字 1 替换为 3 。nums 变为 [3,2] 。 - 将数字 2 替换为 1 。nums 变为 [3,1] 。 - 将数字 3 替换为 2 。nums 变为 [2,1] 。 返回最终数组 [2,1] 。
提示:
n == nums.lengthm == operations.length1 <= n, m <= 105nums中所有数字 互不相同 。operations[i].length == 21 <= nums[i], operations[i][0], operations[i][1] <= 106- 在执行第
i个操作时,operations[i][0]在nums中存在。 - 在执行第
i个操作时,operations[i][1]在nums中不存在。
解题思路
方法一:哈希表
我们先用哈希表 记录数组 中每个数字的下标,然后遍历操作数组 ,对于每个操作 ,我们将 在 中的下标 对应的数字替换为 ,并更新 中 的下标为 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 的长度和操作数组 的长度。
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
d = {x: i for i, x in enumerate(nums)}
for x, y in operations:
nums[d[x]] = y
d[y] = d[x]
return nums
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate identify the need for a hash map to optimize lookups?
- question_mark
Does the candidate recognize the importance of maintaining constant time complexity for updates?
- question_mark
How well does the candidate handle large inputs with the given constraints?
常见陷阱
外企场景- error
Not using a hash map, leading to inefficient scanning for each operation.
- error
Forgetting to update the array after each operation, causing incorrect results.
- error
Overcomplicating the solution by attempting to optimize prematurely without considering basic functionality first.
进阶变体
外企场景- arrow_right_alt
What if we were given an array with duplicate elements? How would the solution change?
- arrow_right_alt
How would the solution be affected if the replacement values could already exist in the array?
- arrow_right_alt
What if the number of operations were much larger than the number of elements in the array?