按既定順序創建目標數組
一、LeetCode題解
瞧一瞧~
- 博健的LeetCode題解:Gitbook版本傳送門
- 博健的LeetCode題解:CSDN傳送門
- 前端進階筆記:Gitbook傳送門
二、算法題
題目
給你兩個整數數組 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]
解法一 (splice)
思路
代碼
var createTargetArray = function(nums, index) {
let target = [];
index.forEach((item, i) => {
target.splice(item, 0, nums[i]);
});
return target;
};