Leetcode——5364. 按既定順序創建目標數組

5364. 按既定順序創建目標數組

給你兩個整數數組 nums 和 index。你需要按照以下規則創建目標數組:

目標數組 target 最初爲空。
按從左到右的順序依次讀取 nums[i] 和 index[i],在 target 數組中的下標 index[i] 處插入值 nums[i] 。
重複上一步,直到在 nums 和 index 中都沒有要讀取的元素。
請你返回目標數組。

題目保證數字插入位置總是存在。

示例 1:

輸入:nums = [0,1,2,3,4], index = [0,1,2,2,1]
輸出:[0,4,1,3,2]
解釋:
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:

輸入:nums = [1,2,3,4,0], index = [0,1,2,3,0]
輸出:[0,1,2,3,4]
解釋:
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]
示例 3:

輸入:nums = [1], index = [0]
輸出:[1]

提示:

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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/create-target-array-in-the-given-order
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解題思路:

直接insert了…

程序代碼(Python):

class Solution:
    def createTargetArray(self, nums, index):
        target = []
        for i, j in zip(nums, index):
            target.insert(j,i)
        return target

程序代碼(C++):

class Solution {
public:
    vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
        vector<int> res;
        for(int i = 0; i < index.size(); ++i){
            res.insert(res.begin()+index[i], nums[i]);
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章