LeetCode 1389. 按既定順序創建目標數組
- 2020 年 4 月 7 日
- 筆記
題目
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]
解題思路
- 因為數組在不斷變化,所以新建一個列表
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/