1470. Shuffle the Array

LeetCode easy original: C# #array #csharp #easy #leetcode
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

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

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

Exemple:

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# solution

correspondant/original
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++ solution

brouillon automatique, à relire avant soumission
#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 solution

correspondant/original
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 solution

correspondant/original
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

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

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

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

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

return tableau result.

😎

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.