Leetcode C++ 《第181場周賽-1》 5364. 按既定順序創建目標數組

Leetcode C++ 《第181場周賽-1》 5364. 按既定順序創建目標數組

1. 題目

給你兩個整數數組 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]

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

2. 思路

  • 直接使用vector的插入啦

3. 代碼

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]);
            /*for (int j = 0; j < res.size(); j++)
                cout << res[j] << " ";
            cout << endl*/
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章