- 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的元素时。之后的每一个元素都会前后或向前改变原有位置。