Leetcode 1389. Create Target Array in the Given Order

  1. Create Target Array in the Given Order
    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]

class Solution {
    public int[] createTargetArray(int[] nums, int[] index) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        int[] target = new int[nums.length];
        for (int i = 0; i < index.length; i++) {
            list.add(index[i],nums[i]);
        }
        for (int i = 0; i < list.size(); i++) {
            target[i] = list.get(i);
        }
        return target;
    }
}

Time Complexity:
O(n^2+n) = O(n^2)
ArrayList在java中,是动态增加Array Size. 根据JDK中的源代码,可以看出ArrayList是动态的数组形式。每当增加一个element,它都会新建一个新的size的Array,然后将旧的Array中的元素移到新的Array中,从而完成增容。
Space Complexity:
O(n)。
分析:
在数组中每一次插入与删除,最坏的情况是n次移动。当插入或者删除index为0的元素时。之后的每一个元素都会前后或向前改变原有位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值