Lectura
Rotar arreglo (Java, Python, PHP, C++, JavaScript)
El ejercicio consiste en rotar un array hacia la derecha un número determinado de veces
Por ejemplo, si tenemos el array nums = [1,2,3,4,5,6,7] y queremos rotarlo k veces, como por ejemplo, 3, el nuevo array se llenará de la siguiente manera: el elemento en la posición 0 (valor 1) se moverá a la posición 3, el elemento en la posición 1 (valor 2) se moverá a la posición 4, y así sucesivamente. Una vez que se llega a la posición 4, se sobrepasa del tamaño final del array y se empieza desde el principio. Es decir, el elemento en la posición 4 (valor 5) se moverá a la posición 0, y así sucesivamente hasta llegar al final del nuevo array [5,6,7,1,2,3,4].
Explicación del ejercicio Paso por paso
Código de la solución
Java
public class Solution {
public static void rotate(int[] nums, int k) {
// step #1
int size = nums.length;
int[] aux = new int[size];
// step #2
for (int i = 0; i < size; i++) {
int position = (i + k) % size;
// step #3
aux[position] = nums[i];
}
// step #4
System.arraycopy(aux, 0, nums, 0, size);
}
}
Python
class Solution(object):
def rotate(self, nums, k):
# step #1
size = len(nums)
aux = [0] * size
# step #2
for i in range(size):
position = (i + k) % size
# step #3
aux[position] = nums[i]
# step #4
nums[:] = aux
PHP
class Solution {
/**
* @param Integer[] $nums
* @param Integer $k
* @return NULL
*/
function rotate(&$nums, $k) {
// step #1
$size = count($nums);
$aux = array_fill(0, $size, 0);
// step #2
for ($i = 0; $i < $size; $i++) {
$position = ($i + $k) % $size;
// step #3
$aux[$position] = $nums[$i];
}
// step #4
for ($i = 0; $i < $size; $i++) {
$nums[$i] = $aux[$i];
}
}
}
C++
class Solution {
public:
void rotate(vector& nums, int k) {
// step #1
int size = nums.size();
vector aux(size);
// step #2
for (int i = 0; i < size; i++) {
int position = (i + k) % size;
// step #3
aux[position] = nums[i];
}
// step #4
nums = aux;
}
};
JavaScript
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
// step #1
const size = nums.length;
const aux = new Array(size);
// step #2
for (let i = 0; i < size; i++) {
const position = (i + k) % size;
// step #3
aux[position] = nums[i];
}
// step #4
for (let i = 0; i < size; i++) {
nums[i] = aux[i];
}
};
Si te gustó el contenido, ¡visita mi canal de YouTube para ver más explicaciones sobre algoritmos y estructuras de datos!