Introduction
Here our problem says, we are given 2 arrays and have to build a new array using those 2. So, in an array there is two part one is index and another one is value in that index. Here the our new array index and its value is separated in two other array one is nums which consist the index value and another one is index array where we have the index value of the new array.
Examples
Steps
- Take a for loop and set the index value to arrIndex and array_value to value
- Check if Same index is arrived before or not using isArrived Method.
- if true then run a for loop and swap the elements to it right from the index value.
- insert the value in the index.
Hints
JavaCode
class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
int[] arr = new int [nums.length];
int arrIndex = 0;
int value = 0;
for(int i = 0; i<nums.length; i++){
arrIndex = index[i];
value = nums[i];
if(isAccess(index, arrIndex, nums.length)){
for(int j = nums.length-2; j>= arrIndex; j-- )
{
arr[j+1] = arr[j];
}
}
arr[arrIndex] = value;
}
return arr;
}
public boolean isAccess(int []arr, int arrIndex, int length){
for(int i = 0; i< length; i++){
if(arr[i] == arrIndex){
return true;
}
}
return false;
}
}
Top comments (0)