题目:
给你一个数组 nums ,数组中有 2n 个元素,按 [x1,x2,…,xn,y1,y2,…,yn] 的格式排列。 请你将数组按
[x1,y1,x2,y2,…,xn,yn] 格式重新排列,返回重排后的数组。
方法一:
按重新排列的顺序依次写入新的列表中。
执行用时: 28 ms
内存消耗: 13.6 MB
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
new_list = []
for i in range(n):
new_list.append(nums[i])
new_list.append(nums[i+n])
return new_list
方法二:
利用列表赋值的形式。
执行用时: 44 ms
内存消耗: 13.6 MB
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
nums[::2],nums[1::2]=nums[:n],nums[n:]
return nums