0%

LeetCode 1470. Shuffle the Array

題目

1
2
3
4
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].

解法思維

跑迴圈再依序加入

1
2
3
4
5
6
7
var shuffle = function(nums, n) {
let result=[]
for (let i = 0; i < n; i++) {
result.push(nums[i],nums[i+n]);
}
return result
};

先用slice()拆分物件,再跑迴圈,依序加回去

1
2
3
4
5
6
7
8
9
var shuffle = function(nums, n) {
let result=[]
let x =nums.slice(0,n)
let y=nums.slice(n)
for (let i = 0; i < x.length; i++) {
result.push(x[i],y[i]);
}
return result
};

slice()

1
2
3
arr.slice()
arr.slice(begin)
arr.slice(begin, end)
1
2
3
4
5
6
7
8
9
10

let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
let fruit1 = fruits.slice(1);
let fruit2 = fruits.slice(1, 3);
let fruit3 = fruits.slice(-3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// fruit1 contains ['Orange', 'Lemon', 'Apple', 'Mango']
// fruit2 contains ['Orange', 'Lemon']
// fruit3 contains ["Lemon", "Apple", "Mango"]