LC 1389.Create Target Array in the Given Order

题目描述

这是 LeetCode 上的 1389. 按既定顺序创建目标数组 ,难度为简单

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

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

请你返回目标数组。

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

示例 1:

1
2
3
4
5
6
7
8
9
输入: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:

1
2
3
4
5
6
7
8
9
输入: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:

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

提示:

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

解答

方法一:模拟

根据题目要求,用链表来模拟插入的过程,最后返回插入完毕之后的链表即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
var list = new ArrayList<Integer>();
for (int i = 0; i < index.length; ++i) {
list.add(index[i], nums[i]);
}
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; ++i) {
res[i] = list.get(i);
}
return res;
}
}
  • 时间复杂度\(O(n^2)\)​,考虑一次操作最坏情况下的时间代价和当前数组中元素的个数呈正比, 第 i 次操作时元素个数为 i - 1 ,所以这里渐进时间复杂度为 \(O(\sum_{i = 1}^n(i - 1)) = O(n^2)\)
  • 空间复杂度\(O(1)\),除了返回值的空间外,没有使用额外的空间。

每题一图


LC 1389.Create Target Array in the Given Order
https://chen-huaneng.github.io/2024/01/08/2024-1-8-2024-01-08-lc-1389/
作者
Abel
发布于
2024年1月8日
更新于
2024年1月8日
许可协议