LeetCode | 1389. Create Target Array in the Given Order按既定顺序创建目标数组【Python】

淡淡的烟草味﹌ 2023-07-18 03:25 103阅读 0赞

LeetCode 1389. Create Target Array in the Given Order按既定顺序创建目标数组【Easy】【Python】【数组】

Problem

LeetCode

Given two arrays of integers nums and index. Your task is to create target array under the following rules:

  • Initially target array is empty.
  • From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
  • Repeat the previous step until there are no elements to read in nums and index.

Return the target array.

It is guaranteed that the insertion operations will be valid.

Example 1:

  1. Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
  2. Output: [0,4,1,3,2]
  3. Explanation:
  4. nums index target
  5. 0 0 [0]
  6. 1 1 [0,1]
  7. 2 2 [0,1,2]
  8. 3 2 [0,1,3,2]
  9. 4 1 [0,4,1,3,2]

Example 2:

  1. Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
  2. Output: [0,1,2,3,4]
  3. Explanation:
  4. nums index target
  5. 1 0 [1]
  6. 2 1 [1,2]
  7. 3 2 [1,2,3]
  8. 4 3 [1,2,3,4]
  9. 0 0 [0,1,2,3,4]

Example 3:

  1. Input: nums = [1], index = [0]
  2. Output: [1]

Constraints:

  • 1 <= nums.length, index.length <= 100
  • nums.length == index.length
  • 0 <= nums[i] <= 100
  • 0 <= index[i] <= i

问题

力扣

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

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

请你返回目标数组。

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

示例 1:

  1. 输入:nums = [0,1,2,3,4], index = [0,1,2,2,1]
  2. 输出:[0,4,1,3,2]
  3. 解释:
  4. nums index target
  5. 0 0 [0]
  6. 1 1 [0,1]
  7. 2 2 [0,1,2]
  8. 3 2 [0,1,3,2]
  9. 4 1 [0,4,1,3,2]

示例 2:

  1. 输入:nums = [1,2,3,4,0], index = [0,1,2,3,0]
  2. 输出:[0,1,2,3,4]
  3. 解释:
  4. nums index target
  5. 1 0 [1]
  6. 2 1 [1,2]
  7. 3 2 [1,2,3]
  8. 4 3 [1,2,3,4]
  9. 0 0 [0,1,2,3,4]

示例 3:

  1. 输入:nums = [1], index = [0]
  2. 输出:[1]

提示:

  • 1 <= nums.length, index.length <= 100
  • nums.length == index.length
  • 0 <= nums[i] <= 100
  • 0 <= index[i] <= i

思路

数组

时间复杂度: O(n),n 为 index 长度,nums 长度和 index 相同。
空间复杂度: O(n),n 为 index 长度。

Python3代码
  1. from typing import List
  2. class Solution:
  3. def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
  4. target = []
  5. for i in range(len(index)):
  6. target.insert(index[i], nums[i]) # insert(位置, 值)
  7. return target

GitHub链接

Python

发表评论

表情:
评论列表 (有 0 条评论,103人围观)

还没有评论,来说两句吧...

相关阅读