Create a target array under the following rules:
- Initially, the 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
nums
andindex.
Example:
Input: nums={0,1,2,3,4}, index={0,1,2,2,1} Output: newArray={0,4,1,3,2}
Approach
Java
import java.util.Arrays;import java.util.LinkedList;public class CreateTargetArrayInGivenOrder {public static void main(String[] args) {int nums[] = { 0, 1, 2, 3, 4 };int index[] = { 0, 1, 2, 2, 1 };int target[] = createTargetArray(nums, index);System.out.println(Arrays.toString(target));}private static int[] createTargetArray(int[] nums, int[] index) {LinkedList<Integer> list = new LinkedList<Integer>();for (int i = 0; i < nums.length; i++) {list.add(index[i], nums[i]);}int[] targetArray = list.stream().mapToInt(Integer::intValue).toArray();return targetArray;}}
C++
#include <bits/stdc++.h>using namespace std;//function to create the arrayvector<int> createTargetArray(vector<int>& nums,vector<int>& index){vector<int> target;int n=nums.size();if(n==0)return target;for(int i=0;i<n;i++)target.insert(target.begin()+index[i],nums[i]);return target;}int main(){vector<int> nums {0,1,2,3,4};vector<int> index ={0,1,2,2,1};vector<int> newArray=createTargetArray(nums,index);for(int i=0;i<newArray.size();i++)cout<<newArray[i]<<" ";return 0;}
No comments:
Post a Comment