Dada una array, invierta cada sub-array formada por k elementos consecutivos.
Ejemplos:
Entrada:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
Salida:
[3, 2, 1, 6, 5, 4, 9, 8, 7]Entrada:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 5
Salida:
[5, 4, 3, 2, 1, 8, 7, 6]Entrada:
arr = [1, 2, 3, 4, 5, 6]
k = 1
Salida:
[1, 2, 3, 4, 5, 6]Entrada:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 10
Salida:
[8, 7, 6, 5, 4, 3, 2, 1]
Enfoque : considere cada subarreglo de tamaño k comenzando desde el principio del arreglo e inviértalo. Necesitamos manejar algunos casos especiales. Si k no es múltiplo de n donde n es el tamaño de la array, para el último grupo nos quedarán menos de k elementos, debemos invertir todos los elementos restantes. Si k = 1 , la array debe permanecer sin cambios. Si k >= n, invertimos todos los elementos presentes en el arreglo.
La imagen de abajo es una ejecución en seco del enfoque anterior:
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to reverse every sub-array formed by // consecutive k elements #include <iostream> using namespace std; // Function to reverse every sub-array formed by // consecutive k elements void reverse(int arr[], int n, int k) { for (int i = 0; i < n; i += k) { int left = i; // to handle case when k is not multiple of n int right = min(i + k - 1, n - 1); // reverse the sub-array [left, right] while (left < right) swap(arr[left++], arr[right--]); } } // Driver code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); reverse(arr, n, k); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0; }
Java
// Java program to reverse every sub-array formed by // consecutive k elements class GFG { // Function to reverse every sub-array formed by // consecutive k elements static void reverse(int arr[], int n, int k) { for (int i = 0; i < n; i += k) { int left = i; // to handle case when k is not multiple // of n int right = Math.min(i + k - 1, n - 1); int temp; // reverse the sub-array [left, right] while (left < right) { temp=arr[left]; arr[left]=arr[right]; arr[right]=temp; left+=1; right-=1; } } } // Driver method public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int k = 3; int n = arr.length; reverse(arr, n, k); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } } // This code is contributed by Anant Agarwal.
Python3
# Python 3 program to reverse every # sub-array formed by consecutive k # elements # Function to reverse every sub-array # formed by consecutive k elements def reverse(arr, n, k): i = 0 while(i<n): left = i # To handle case when k is not # multiple of n right = min(i + k - 1, n - 1) # Reverse the sub-array [left, right] while (left < right): arr[left], arr[right] = arr[right], arr[left] left+= 1; right-=1 i+= k # Driver code arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 3 n = len(arr) reverse(arr, n, k) for i in range(0, n): print(arr[i], end =" ") # This code is contributed by Smitha Dinesh Semwal
C#
// C# program to reverse every sub-array // formed by consecutive k elements using System; class GFG { // Function to reverse every sub-array // formed by consecutive k elements public static void reverse(int[] arr, int n, int k) { for (int i = 0; i < n; i += k) { int left = i; // to handle case when k is // not multiple of n int right = Math.Min(i + k - 1, n - 1); int temp; // reverse the sub-array [left, right] while (left < right) { temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left += 1; right -= 1; } } } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7, 8}; int k = 3; int n = arr.Length; reverse(arr, n, k); for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } } } // This code is contributed // by Shrikant13
PHP
<?php // PHP program to reverse every sub-array // formed by consecutive k elements // Function to reverse every sub-array // formed by consecutive k elements function reverse($arr, $n, $k) { for ($i = 0; $i < $n; $i += $k) { $left = $i; // to handle case when k is not // multiple of n $right = min($i + $k - 1, $n - 1); $temp; // reverse the sub-array [left, right] while ($left < $right) { $temp = $arr[$left]; $arr[$left] = $arr[$right]; $arr[$right] = $temp; $left += 1; $right -= 1; } } return $arr; } // Driver Code $arr = array(1, 2, 3, 4, 5, 6, 7, 8); $k = 3; $n = sizeof($arr); $arr1 = reverse($arr, $n, $k); for ($i = 0; $i < $n; $i++) echo $arr1[$i] . " "; // This code is contributed // by Akanksha Rai ?>
Javascript
<script> // Javascript program to reverse every sub-array // formed by consecutive k elements // Function to reverse every sub-array // formed by consecutive k elements function reverse(arr, n, k) { for(let i = 0; i < n; i += k) { let left = i; // To handle case when k is not // multiple of n let right = Math.min(i + k - 1, n - 1); let temp; // Reverse the sub-array [left, right] while (left < right) { temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left += 1; right -= 1; } } return arr; } // Driver Code let arr = new Array(1, 2, 3, 4, 5, 6, 7, 8); let k = 3; let n = arr.length; let arr1 = reverse(arr, n, k); for(let i = 0; i < n; i++) document.write(arr1[i] + " "); // This code is contributed by saurabh jaiswal </script>
C
// C program to reverse every sub-array formed by // consecutive k elements #include <stdio.h> // Function to reverse every sub-array formed by // consecutive k elements void reverse(int arr[], int n, int k) { for (int i = 0; i < n; i += k) { int left = i; int right; // to handle case when k is not multiple of n if(i+k-1<n-1) right = i+k-1; else right = n-1; // reverse the sub-array [left, right] while (left < right) { // swap int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } } // Driver code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); reverse(arr, n, k); for (int i = 0; i < n; i++) printf("%d ",arr[i]); return 0; } // This code is contributed by Arpit Jain
Producción:
3 2 1 6 5 4 8 7
La complejidad temporal de la solución anterior es O(n).
El espacio auxiliar utilizado por el programa es O(1).
Este artículo es una contribución de Aditya Goel . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA