1470. Shuffle the Array

LeetCode easy original: C# #array #csharp #easy #leetcode
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

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

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

Beispiel:

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# Lösung

zugeordnet/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++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#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 Lösung

zugeordnet/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 Lösung

zugeordnet/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

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

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

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

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

return Array result.

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.