Create Target Array in the Given Order
You are given two arrays nums
and index
. You have to create a target array by inserting the elements from nums
at the positions specified by index
.
Approach
- Initialize an empty target list.
- Iterate through
nums
andindex
simultaneously using a loop. - Use the
insert()
method to insert the elementnums[i]
at positionindex[i]
in the target list. - Continue until all elements from
nums
are processed. - Return the target list.
Here’s the code implementing this approach:
|
|
Example
Let’s take nums = [0,1,2,3,4]
and index = [0,1,2,2,1]
as an example:
- Insert
0
at index0
: target =[0]
- Insert
1
at index1
: target =[0,1]
- Insert
2
at index2
: target =[0,1,2]
- Insert
3
at index2
: target =[0,1,3,2]
- Insert
4
at index1
: target =[0,4,1,3,2]
So the output will be [0,4,1,3,2]
.
This solution is simple and easy to understand for beginners. It directly implements the instructions given in the problem statement, using the insert()
method provided by Python’s list class.