1470. Shuffle the Array
Task text is translated from Russian for the selected interface language. Code is left unchanged.
Дан array nums, состоящий из 2n elementов в форме [x1, x2, ..., xn, y1, y2, ..., yn].
return array в форме [x1, y1, x2, y2, ..., xn, yn].
Example:
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
matched/originalpublic 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
auto-draft, review before submit#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
matched/originalclass 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
matched/originalfunc 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.
😎
Vacancies for this task
Active vacancies with overlapping task tags are shown.
There are no active vacancies yet.