LeetCode刷题:1389.按给定顺序创建目标数组. Create Target Array in the Given Order
给定两个整数数组 nums和index。您的任务是根据以下规则创建目标数组:
最初目标数组为空。
从左到右读NUMS [i]和指数[I],插入在指数index[i] 的值nums[i] 在 目标阵列。
重复上述步骤,直到没有元素在阅读nums和index.
返回目标数组。
保证插入操作将是有效的。
范例1:
输入: nums = [0,1,2,3,4],索引= [0,1,2,2,1]
输出: [0,4,1,3,2]
说明:
nums索引目标
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],索引= [0,1,2,3,0]
输出: [0,1,2,3,4]
说明:
nums索引目标
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],索引= [0]
输出: [1]
限制条件:
1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i
class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
List<Integer> list = new ArrayList<>();
int[] res = new int[nums.length];
for(int i=0;i<nums.length;i++){
if(i>index.length){
break;
}
list.add(index[i],nums[i]);
//往list集合里插入值,nums是值,index是下标索引
//插入后原本索引右往移动一位
}
for(int j=0;j<list.size();j++){
res[j]=list.get(j);
//get方法将list的值赋给res数组
}
return res;
}
}