Leetcode 1389. Create Target Array in the Given Order
Given two arrays nums
and index
. Your task is to create a target array under the following rules:
nums
into target
at the positions specified by index
. Specifically, target[index[i]]
should be nums[i]
.Return the target array.
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]
nums
and index
arrays?
index
will always contain valid positions for insertion)?
nums
and index
simultaneously.nums
, insert it into the target array at the position provided by the corresponding element in index
.In C++, we can use the insert
method of the vector
class to perform the insertion at specific index positions.
#include <iostream>
#include <vector>
std::vector<int> createTargetArray(const std::vector<int>& nums, const std::vector<int>& index) {
std::vector<int> target;
for (size_t i = 0; i < nums.size(); ++i) {
target.insert(target.begin() + index[i], nums[i]);
}
return target;
}
int main() {
// Sample input
std::vector<int> nums = {0, 1, 2, 3, 4};
std::vector<int> index = {0, 1, 2, 2, 1};
// Function call
std::vector<int> target = createTargetArray(nums, index);
// Output result
for (int num : target) {
std::cout << num << " ";
}
return 0;
}
insert
which can be expensive. Each insertion operation takes (O(n)) in the worst case because elements need to be shifted to the right to make space. Since there are n
insertions, the overall complexity is (O(n^2)).However, given the constraints (maximum length of 100), this quadratic time complexity is manageable for this problem size.
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?