[LeetCode] 1389. Create the target array in a predetermined order (C++)

1 topic description

Give you two integer arrays nums and index. You need to create the target array according to the following rules:

  • The target array target is initially empty.
  • Read nums[i] and index[i] in order from left to right, the subscript in the target array
  • Insert the value nums[i] at index[i].
  • Repeat the previous step until there are no elements to be read in nums and index.
    Please return the target array.
    The title guarantees that the number insertion position always exists.

2 Example description

2.1 Example 1

Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]

Explanation:

nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]

2.2 Example 2

Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]

Explanation:

nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]

2.3 Example 3

Input: nums = [1], index = [0]
Output: [1]

3 Problem solving tips

1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i

4 Detailed source code (C++)

class Solution {
    
    
public:
    vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
    
    
        vector<int> res;
        for (int i = 0 ; i < nums.size() ; i ++)
        {
    
    
            res.insert(res.begin() + index[i] , nums[i]);
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114001117