leetcode 1470. 重新排列數組(周賽192)

【題目】1470. 重新排列數組

給你一個數組 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

【解題思路1】

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] ans = new int[n * 2];
        int i = 0;
        for(int j = 0; j < n * 2; j += 2){
            ans[j] = nums[i];
            ans[j + 1] = nums[i + n];
            i++;
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章