1389. Creating target array according to the established order

topic:

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 the nums [i] and the index [i], the subscript index in the target array [i] of the interpolation value nums [i].
Repeat the previous step, the elements until nums and index are not to be read.
Please return to the target array.

Topic ensure that the digital insertion position is always there.

 

Example 1:

Input: 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]
1 1 [0]
2 2 [0, 1]
3 2 [0,1,3,2]
41 [0,4,1,3,2]
example 2:

Input: 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: 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

Problem-solving ideas:

1. cnt an auxiliary array used to record the number of each element in the original array index occurs, the initial value of -1

2. traversing original array index, if there have been no earlier than the current element, i.e. cnt [index [i]] == - 1, then the current nums array element corresponding to the i-th nums [i] on the index [i] at that res [index [i]] = nums [i]; and accumulating the index [i] is the number of occurrences, i.e. cnt [index [i]] ++;

3. If there have been prior to the current element, then the index [i] in and after a backward elements, vacated index [i] position, to a new element, i.e.,

for(int j=s-2;j>=index[i];--j){

       res[j+1]=res[j];

}

res[index[i]]=nums[i];

Code:

class Solution {
public:
    vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
        int s=nums.size();
        int cnt[101]={-1};
        vector<int> res(s);
        for(int i=0;i<s;++i){
            if(cnt[index[i]]>=0){//后移元素
                for(int j=s-2;j>=index[i];--j){
                    res[j+1]=res[j];
                }
                res[index[i]]=nums[i];
            }
            else{
                res[index[i]]=nums[i];
                cnt[index[i]]++;
            }
        }
        return res;
    }
};

Time-consuming and memory usage: 

Published 253 original articles · won praise 15 · views 30000 +

Guess you like

Origin blog.csdn.net/junjunjiao0911/article/details/105180756