leetcode 1470 重新排列數組

1470. 重新排列數組

題目描述

給你一個數組 nums ,數組中有 2n 個元素,按 [x1,x2,…,xn,y1,y2,…,yn] 的格式排列。
請你將數組按 [x1,y1,x2,y2,…,xn,yn] 格式重新排列,返回重排後的數組。
示例:
輸入: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]

解題思路

數組長度爲2n,那麼每次插入第i(0i<n0 \le i < n)個數據時,順便插入第i+n個數據即可。

python3 實現

class Solution(object):
    def shuffle(self, nums, n):
        """
        :type nums: List[int]
        :type n: int
        :rtype: List[int]
        """
        res = []
        for i in range(n):
            res.append(nums[i])
            res.append(nums[i+n])
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章