LeetCode 题解工作台
按既定顺序创建目标数组
给你两个整数数组 nums 和 index 。你需要按照以下规则创建目标数组: 目标数组 target 最初为空。 按从左到右的顺序依次读取 nums[i] 和 index[i] ,在 target 数组中的下标 index[i] 处插入值 nums[i] 。 重复上一步,直到在 nums 和 in…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
我们创建一个列表 ,用于存储目标数组。由于题目保证数字插入位置总是存在,因此我们可以直接按照给定的顺序插入到对应的位置。 时间复杂度 ,空间复杂度 。其中 是数组的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组:
- 目标数组
target最初为空。 - 按从左到右的顺序依次读取
nums[i]和index[i],在target数组中的下标index[i]处插入值nums[i]。 - 重复上一步,直到在
nums和index中都没有要读取的元素。
请你返回目标数组。
题目保证数字插入位置总是存在。
示例 1:
输入:nums = [0,1,2,3,4], index = [0,1,2,2,1] 输出:[0,4,1,3,2] 解释: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2]
示例 2:
输入:nums = [1,2,3,4,0], index = [0,1,2,3,0] 输出:[0,1,2,3,4] 解释: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4]
示例 3:
输入:nums = [1], index = [0] 输出:[1]
提示:
1 <= nums.length, index.length <= 100nums.length == index.length0 <= nums[i] <= 1000 <= index[i] <= i
解题思路
方法一:模拟
我们创建一个列表 ,用于存储目标数组。由于题目保证数字插入位置总是存在,因此我们可以直接按照给定的顺序插入到对应的位置。
时间复杂度 ,空间复杂度 。其中 是数组的长度。
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
target = []
for x, i in zip(nums, index):
target.insert(i, x)
return target
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) for array insertions due to shifting elements, while space complexity is O(n) for storing the target array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for correct handling of index-based insertions without overwriting existing elements.
- question_mark
Expect candidates to simulate array operations rather than attempting complex mathematical formulas.
- question_mark
Watch for off-by-one errors when elements need to shift to accommodate new insertions.
常见陷阱
外企场景- error
Overwriting elements instead of shifting them during insertion.
- error
Ignoring the correct order of operations, which can produce incorrect target arrays.
- error
Assuming indexes are sorted or that insertions do not require dynamic adjustments.
进阶变体
外企场景- arrow_right_alt
Creating a target array with duplicate values in nums, testing stability of insertions.
- arrow_right_alt
Using extremely large arrays to explore time complexity limits of the simulation approach.
- arrow_right_alt
Modifying the problem to remove guarantees about valid insertions, requiring bounds checks.