LeetCode 题解工作台

按既定顺序创建目标数组

给你两个整数数组 nums 和 index 。你需要按照以下规则创建目标数组: 目标数组 target 最初为空。 按从左到右的顺序依次读取 nums[i] 和 index[i] ,在 target 数组中的下标 index[i] 处插入值 nums[i] 。 重复上一步,直到在 nums 和 in…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·模拟

bolt

答案摘要

我们创建一个列表 ,用于存储目标数组。由于题目保证数字插入位置总是存在,因此我们可以直接按照给定的顺序插入到对应的位置。 时间复杂度 ,空间复杂度 。其中 是数组的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个整数数组 numsindex。你需要按照以下规则创建目标数组:

  • 目标数组 target 最初为空。
  • 按从左到右的顺序依次读取 nums[i]index[i],在 target 数组中的下标 index[i] 处插入值 nums[i]
  • 重复上一步,直到在 numsindex 中都没有要读取的元素。

请你返回目标数组。

题目保证数字插入位置总是存在。

 

示例 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 <= 100
  • nums.length == index.length
  • 0 <= nums[i] <= 100
  • 0 <= index[i] <= i
lightbulb

解题思路

方法一:模拟

我们创建一个列表 targettarget,用于存储目标数组。由于题目保证数字插入位置总是存在,因此我们可以直接按照给定的顺序插入到对应的位置。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n)O(n)。其中 nn 是数组的长度。

1
2
3
4
5
6
7
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

按既定顺序创建目标数组题解:数组·模拟 | LeetCode #1389 简单