示例 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]
list
,作为存储不断变化的“数组”;nums
和index
从左到右依次读取,利用列表的add()
方法,将下标 index[i]
处插入值 nums[i]
;int
数组,所以新建一个int
数组target
;list
转换为target
;target
;package Array;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* Version : 1.0
* Author : cunyu
* Email : cunyu1024@foxmail.com
* Website : https://cunyu1943.github.io
* Date : 2020/3/26 10:55
* Project : LeetCode
* Package : Array
* Class : OneThreeEightNine
* Desc : 1389. 按既定顺序创建目标数组
*/
public class OneThreeEightNine {
public static void main(String[] args) throws Exception {
OneThreeEightNine oneThreeEightNine = new OneThreeEightNine();
int[] nums = {0, 1, 2, 3, 4};
int[] index = {0, 1, 2, 2, 1};
for (int item : oneThreeEightNine.createTargetArray(nums, index)
) {
System.out.println(item);
}
}
public int[] createTargetArray(int[] nums, int[] index) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length;i++){
list.add(index[i],nums[i]);
}
int[] target = new int[nums.length];
for (int i = 0; i < list.size(); i++) {
target[i] = list.get(i);
}
return target;
}
}
[1]
1389. 按既定顺序创建目标数组: https://leetcode-cn.com/problems/create-target-array-in-the-given-order/