LeetCode 1389. 按既定顺序创建目标数组

题目

1389. 按既定顺序创建目标数组[1]

描述

示例 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]

解题思路

  1. 因为数组在不断变化,所以新建一个列表list,作为存储不断变化的“数组”;
  2. numsindex从左到右依次读取,利用列表的add()方法,将下标 index[i] 处插入值 nums[i]
  3. 因为最终返回值是int数组,所以新建一个int数组target
  4. list转换为target
  5. 返回target;

实现

package Array;    import java.util.ArrayList;    /**   * Created with IntelliJ IDEA.   * Version : 1.0   * Author  : cunyu   * Email   : [email protected]   * 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/