Leetcode 1389. Create Target Array in the Given Order
Given two arrays of integers nums
and index
. Your task is to create a target array under the following rules:
nums
and its corresponding index from index
.nums
at the position given by index
.Return the target array.
It is guaranteed that the insertion positions will be valid.
nums.length == index.length
nums
and index
are non-empty arrays.1 <= nums.length, index.length <= 100
).nums
at positions defined by index
.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]
target
.nums
and index
.nums
at the specified position from index
into the target
list.target
to an array and return it.O(n)
time in the worst case, where n
is the number of elements in the list at the time of insertion.n
insertions, the time complexity will be O(n^2)
.import java.util.ArrayList;
import java.util.List;
public class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
List<Integer> target = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
target.add(index[i], nums[i]);
}
// Convert the target list to array
int[] result = new int[target.size()];
for (int i = 0; i < target.size(); i++) {
result[i] = target.get(i);
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {0, 1, 2, 3, 4};
int[] index = {0, 1, 2, 2, 1};
int[] result = sol.createTargetArray(nums, index);
for (int num : result) {
System.out.print(num + " ");
}
}
}
This code snippet defines a Solution
class with a method createTargetArray
taking two integer arrays nums
and index
, and produces the desired target array following the insertion rules specified in the problem. The main method also includes an example to demonstrate the usage of the function.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?