189. Rotate Array
O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.
Для целочисленного arrayа nums, поreturn array вправо на k шагов, где k — неотрицательное number.
Exemplo:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
C# solução
correspondente/originalpublic class Solution {
public void Rotate(int[] nums, int k) {
int n = nums.Length;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[(i + k) % n] = nums[i];
}
for (int i = 0; i < n; i++) {
nums[i] = a[i];
}
}
}
C++ solução
rascunho automático, revisar antes de enviar#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 void Rotate(vector<int>& nums, int k) {
int n = nums.size();
vector<int>& a = new int[n];
for (int i = 0; i < n; i++) {
a[(i + k) % n] = nums[i];
}
for (int i = 0; i < n; i++) {
nums[i] = a[i];
}
}
}
Java solução
correspondente/originalclass Solution {
public void rotate(int[] nums, int k) {
int[] a = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
a[(i + k) % nums.length] = nums[i];
}
for (int i = 0; i < nums.length; i++) {
nums[i] = a[i];
}
}
}
JavaScript solução
correspondente/originalclass Solution {
rotate(nums, k) {
const n = nums.length;
const a = new Array(n);
for (let i = 0; i < n; i++) {
a[(i + k) % n] = nums[i];
}
for (let i = 0; i < n; i++) {
nums[i] = a[i];
}
}
}
Python solução
correspondente/originalclass Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
a = [0] * n
for i in range(n):
a[(i + k) % n] = nums[i]
nums[:] = a
Go solução
correspondente/originalpackage main
func rotate(nums []int, k int) {
n := len(nums)
a := make([]int, n)
for i := 0; i < n; i++ {
a[(i+k)%n] = nums[i]
}
for i := 0; i < n; i++ {
nums[i] = a[i]
}
}
Algorithm
1️⃣
Создаем дополнительный array, в который будем помещать каждый element исходного arrayа на его новую позицию. element на позиции i в исходном arrayе будет размещен на индексе (i+k) % длина arrayа.
2️⃣
Копируем elementы из нового arrayа в исходный array, сохраняя новый порядок elementов.
3️⃣
Заменяем исходный array полученным результатом, завершая процесс поворота arrayа.
😎
Vacancies for this task
vagas ativas with overlapping task tags are mostradas.
Ainda não há vagas ativas.