【JavaScript】【Leetcode】Shuffle the Array
--
題目連結
https://leetcode.com/problems/shuffle-the-array/
題目難度
Easy
題目說明
Given the array nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn].
Return the array in the form [x1,y1,x2,y2,…,xn,yn].
給一個數量為2n的陣列如下:
[x1,x2,…,xn,y1,y2,…,yn]
將其轉換為[x1,y1,x2,y2,…,xn,yn]後return
題目範例
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
解題思路
第一種:
假設nums = [0,1,2,3,4,5], n=3,那原本陣列與排序過的陣列比較如下:
原陣列:[0, 1, 2, 3, 4, 5]
新陣列:[0, 3, 1, 4, 2, 5]
index值變化:
0:0→0
1:1→2
2:2→4
3:3→1
4:4→3
5:5→5
當index<n時:
new index = index*2
而當index≥n時:
new index = (index-n)*2+1
因此,可得出解答如下:
var shuffle = function(nums, n) {
let newArray=[]; //宣告新陣列,存放new array
for(i=0;i<nums.length;i++){
if(i<n){
newArray[i*2] = nums[i]; //當index<n
}else{
newArray[(i-n)*2+1] = nums[i]; //當index≥n,
}
}
return newArray; //回傳結果
};
第二種:
一樣假設nums = [0,1,2,3,4,5], n=3。首先,我們先來模擬程式一步一步執行找出規則:
第一步:[0]->original index=0
第二步:[0,3]->original index=3=0+3
第三步:[0,3,1]->original index=1
第四步:[0,3,1,4]->original index=4=1+3
第五步:[0,3,1,4,2]->original index=1
第六步:[0,3,1,4,2,5]->original index=5=2+3
於是,我們可以用push()的方式,在push第一個數字完之後,對第一個數字的index值+3後再push一次,得出解法如下:
var shuffle = function(nums,n) {
let result = [];
for(let i=0;i<n; i++){
result.push(nums[i]);
result.push(nums[i + n]);
}
return result;
};