Create a destination array (leetcode181 week tournament) according to the established order

Give you two integer array numsand index. You need to create the target array in accordance with the following rules:

  • Target array targetis initially empty.
  • Sequentially read from left to right nums[i]and index[i], in targetsuperscript array index[i]at the interpolated values nums[i].
  • Repeat the previous step, until numsand indexelements 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 }

 

Guess you like

Origin www.cnblogs.com/ZhengLijie/p/12545177.html