1470. Shuffle the Array

LeetCode easy original: C# #array #csharp #easy #leetcode
選択した UI 言語に合わせて問題文をロシア語から翻訳します。コードは変更しません。

Дан 配列 nums, состоящий из 2n elementов в форме [x1, x2, ..., xn, y1, y2, ..., yn].

return 配列 в форме [x1, y1, x2, y2, ..., xn, yn].

例:

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].

C# 解法

照合済み/オリジナル
public class Solution {
    public int[] Shuffle(int[] nums, int n) {
        int[] result = new int[2 * n];
        for (int i = 0; i < n; ++i) {
            result[2 * i] = nums[i];
            result[2 * i + 1] = nums[n + i];
        }
        return result;
    }
}

C++ 解法

自動ドラフト、提出前に確認
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public vector<int>& Shuffle(vector<int>& nums, int n) {
        vector<int>& result = new int[2 * n];
        for (int i = 0; i < n; ++i) {
            result[2 * i] = nums[i];
            result[2 * i + 1] = nums[n + i];
        }
        return result;
    }
}

Java 解法

照合済み/オリジナル
class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] result = new int[2 * n];
        for (int i = 0; i < n; ++i) {
            result[2 * i] = nums[i];
            result[2 * i + 1] = nums[n + i];
        }
        return result;
    }
}

Go 解法

照合済み/オリジナル
func shuffle(nums []int, n int) []int {
    result := make([]int, 2*n)
    for i := 0; i < n; i++ {
        result[2*i] = nums[i]
        result[2*i+1] = nums[n+i]
    }
    return result
}

Algorithm

Создайте 配列 result размером 2 * n.

Итеративно пройдите по 配列у nums от 0 до n - 1:

Сохраните element xi+1, то есть nums[i], в индекс 2 * i 配列а result.

Сохраните element yi+1, то есть nums[i + n], в индекс 2 * i + 1 配列а result.

return 配列 result.

😎

Vacancies for this task

有効な求人 with overlapping task tags are 表示.

すべての求人
有効な求人はまだありません。