Given two arrays of integers
It is guaranteed that the insertion operations will be valid.
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 valuenums[i]in target array. - Repeat the previous step until there are no elements to read in
numsandindex.
It is guaranteed that the insertion operations will be valid.
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]
Solution in C++:
vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
int *a = nullptr;
int size = nums.size();
a = (int*)calloc(sizeof(int), size);
a[0] = nums.at(0);
for(int iter = 1; iter < size; ++iter){
if(iter > index.at(iter)){
for(int j = 0; j < iter - index.at(iter); ++j){
int temp = a[iter - j];
a[iter - j] = a[iter - j -1];
a[iter - j - 1] = temp;
}
}
a[index.at(iter)] = nums.at(iter);
}
vector<int> ret;
for(int iter = 0; iter < size; ++iter){
ret.push_back(a[iter]);
}
free(a);
return ret;
}
Comments
Post a Comment