Give you two integer array nums
and index
. You need to create the target array in accordance with the following rules:
- Target array
target
is initially empty. - Sequentially read from left to right
nums[i]
andindex[i]
, intarget
superscript arrayindex[i]
at the interpolated valuesnums[i]
. - Repeat the previous step, until
nums
andindex
elements are not to be read.
Please return to the target array.
Topic ensure that the digital insertion position is always there.
Example 1:
Input: the nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] explained: the nums target index 0 0 [ 0] 11 [0] 22 [0, 1] 3 2 [0,1,3,2] 41 [0,4,1,3,2]
Example 2:
Input: the nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] explained: the nums target index . 1 0 [ 1] 21 [1] 32 [1, 2,3] 43 [1,2,3,4] 0 0 [0,1,2,3,4]
Example 3:
Input: the nums = [1], index = [0] Output: [1]
prompt:
1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i
Four questions, two will be the second road running overtime, on this question through, too dishes, and,
Idea: after shifting array element inserted
1 int* createTargetArray(int* nums, int numsSize, int* index, int indexSize, int* returnSize) 2 { 3 int *target; 4 int i; 5 6 target = (int *)malloc(sizeof(int) * indexSize); 7 memset(target,0,indexSize); 8 9 for(i=0; i<indexSize; i++) 10 { 11 if(i == 0) 12 { 13 target[index[i]] = nums[i]; 14 } 15 else //把target中的数后移 16 { 17 for(int j = indexSize-1; j > index[i]; j--) 18 { 19 target[j] = target[j-1]; 20 } 21 target[index[i]] = nums[i]; 22 } 23 24 } 25 26 *returnSize = indexSize; 27 return target; 28 }