LeetCode 题解工作台
基于排列构建数组
给你一个 从 0 开始的排列 nums ( 下标也从 0 开始 )。请你构建一个 同样长度 的数组 ans ,其中,对于每个 i ( 0 ),都满足 ans[i] = nums[nums[i]] 。返回构建好的数组 ans 。 从 0 开始的排列 nums 是一个由 0 到 nums.length …
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
我们可以直接模拟题目描述的过程,构建一个新的数组 ,对于每个 ,令 $\textit{ans}[i] = \textit{nums}[\textit{nums}[i]]$。 时间复杂度 ,其中 是数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你一个 从 0 开始的排列 nums(下标也从 0 开始)。请你构建一个 同样长度 的数组 ans ,其中,对于每个 i(0 <= i < nums.length),都满足 ans[i] = nums[nums[i]] 。返回构建好的数组 ans 。
从 0 开始的排列 nums 是一个由 0 到 nums.length - 1(0 和 nums.length - 1 也包含在内)的不同整数组成的数组。
示例 1:
输入:nums = [0,2,1,5,3,4]
输出:[0,1,2,4,5,3]
解释:数组 ans 构建如下:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
= [0,1,2,4,5,3]
示例 2:
输入:nums = [5,0,1,2,3,4]
输出:[4,5,0,1,2,3]
解释:数组 ans 构建如下:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
= [4,5,0,1,2,3]
提示:
1 <= nums.length <= 10000 <= nums[i] < nums.lengthnums中的元素 互不相同
进阶:你能在不使用额外空间的情况下解决此问题吗(即 O(1) 内存)?
解题思路
方法一:模拟
我们可以直接模拟题目描述的过程,构建一个新的数组 ,对于每个 ,令 。
时间复杂度 ,其中 是数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[num] for num in nums]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Does the candidate directly simulate the process described in the statement?
- question_mark
Does the candidate maintain O(1) space complexity in their solution?
- question_mark
Does the candidate handle edge cases and large input sizes correctly?
常见陷阱
外企场景- error
Confusing the problem with a more complex array manipulation task, forgetting to follow the direct simulation approach.
- error
Using extra space beyond O(1), which violates the problem’s constraints on space efficiency.
- error
Overlooking edge cases such as very small or very large arrays, causing the solution to fail in certain scenarios.
进阶变体
外企场景- arrow_right_alt
Modify the problem to handle multi-dimensional arrays.
- arrow_right_alt
Consider implementing a more complex simulation with different mapping rules.
- arrow_right_alt
Increase the size of the array significantly, ensuring the solution scales efficiently.