題目描述:
給你一個數組 nums ,數組中有 2n 個元素,按 [x1,x2,…,xn,y1,y2,…,yn] 的格式排列。
請你将數組按 [x1,y1,x2,y2,…,xn,yn] 格式重新排列,傳回重排後的數組。
示例 1:
輸入:nums = [2,5,1,3,4,7], n = 3
輸出:[2,3,5,4,1,7]
解釋:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,是以答案為 [2,3,5,4,1,7]
示例 2:
輸入:nums = [1,2,3,4,4,3,2,1], n = 4
輸出:[1,4,2,3,3,2,4,1]
示例 3:
輸入:nums = [1,1,2,2], n = 2
輸出:[1,2,1,2]
提示:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
new_l=nums[0:n];
for i in range(n):
index=2*i+1
new_l.insert(index,nums[i+n])
return new_l
思路:
可以利用python的insert而不是append,因為可以先取出所有x,再把y分别插進去。