LeetCode(Array)1389. Create Target Array in the Given Order
1.问题
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:
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
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]
Example 2:
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
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]
Example 3:
Input: nums = [1], index = [0]
Output: [1]
Constraints:
- 1 <= nums.length, index.length <= 100
- nums.length == index.length
- 0 <= nums[i] <= 100
- 0 <= index[i] <= i
2. 解题思路
方法1:
1.定义一个target的数组,数组长度和nums的长度相等
2.遍历数组
1)如果index的索引和数组遍历索引值相等,target的索引对应的值和nums的索引对应的值相等
2)如果index的索引和数组遍历索引值不相等,要添加一个元素,要从最后向后移动,一直移动到选中下标的位置
倒数第二个元素的值移动到倒数第一元素的位置将其覆盖
指定下标赋值
3.返回target
方法2:
1.定义一个List
2.遍历数组,添加到List中.根据list的扩容,在指定索引添加值,索引处原来的值自动向后移动
3.新建一个数组
4.遍历数组,list的值放入到数组中
5.返回result
3. 代码
代码1:
class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
int[] target = new int[nums.length];//1.定义一个target的数组,数组长度和nums的长度相等
for (int i = 0; i < index.length; i++){ //2.遍历数组
if (index[i] == i) {//1)如果index的索引和数组遍历索引值相等,target的索引对应的值和nums的索引对应的值相等
target[i] = nums[i];
} else { //2)如果index的索引和数组遍历索引值不相等,要添加一个元素,要从最后向后移动,一直移动到选中下标的位置
for (int j = i; j > index[i]; j--) {
target[j] = target[j - 1];//倒数第二个元素的值移动到倒数第一元素的位置将其覆盖
}
target[index[i]] = nums[i];//指定下标赋值
}
}
return target;//3.返回target
}
}
以下代码和代码1的解题思路基本相同,不同的地方在判断的时候i的索引大于index[i] 的值
public int[] createTargetArray(int[] nums, int[] index) {
int[] target = new int[nums.length];
for(int i = 0; i < nums.length; i++)
{
int idx = index[i];
if(idx < i)
{
for(int j = i; j > idx; j--)
target[j] = target[j-1];
}
target[idx] = nums[i];
}
return target;
}
代码2:
public int[] createTargetArray(int[] nums, int[] index) {
List<Integer> list = new ArrayList<>(); //1.定义一个List
for (int i = 0; i < index.length; i++) {//2.遍历数组,添加到List中.根据list的扩容,在指定索引添加值,索引处原来的值自动向后移动
list.add(index[i], nums[i]);
}
int[] target = new int[nums.length];//3.新建一个数组
for (int i = 0; i < index.length; i++) {//4.遍历数组,list的值放入到数组中
target[i] = list.get(i);
}
return target;//5.返回result
}
以下代码和代码2的思路基本相同,不同的地方是for循环换成for each
public int[] createTargetArray(int[] nums, int[] index) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
list.add(index[i], nums[i]);
}
int[] target = new int[nums.length];
int j = 0;
for(Integer temp : list){
target[j++] = temp;
}
return target;
}
}