The key idea is to simulate the process described in the problem: for each value in nums, insert it at the specified position in index. This is efficient for small arrays and directly models the problem statement.
classSolution {
public: vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
vector<int> ans;
for (int i =0; i < nums.size(); ++i) {
ans.insert(ans.begin() + index[i], nums[i]);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
funccreateTargetArray(nums []int, index []int) []int {
ans:= []int{}
fori, v:=rangenums {
idx:=index[i]
ans = append(ans, 0)
copy(ans[idx+1:], ans[idx:])
ans[idx] = v }
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicint[]createTargetArray(int[] nums, int[] index) {
List<Integer> ans =new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
ans.add(index[i], nums[i]);
}
int[] res =newint[ans.size()];
for (int i = 0; i < ans.size(); i++) res[i]= ans.get(i);
return res;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funcreateTargetArray(nums: IntArray, index: IntArray): IntArray {
val ans = mutableListOf<Int>()
for (i in nums.indices) {
ans.add(index[i], nums[i])
}
return ans.toIntArray()
}
}
1
2
3
4
5
6
classSolution:
defcreateTargetArray(self, nums: list[int], index: list[int]) -> list[int]:
ans = []
for v, i in zip(nums, index):
ans.insert(i, v)
return ans
1
2
3
4
5
6
7
8
9
impl Solution {
pubfncreate_target_array(nums: Vec<i32>, index: Vec<i32>) -> Vec<i32> {
letmut ans = Vec::new();
for (v, &i) in nums.iter().zip(index.iter()) {
ans.insert(i asusize, *v);
}
ans
}
}