Reverter um array em grupos de determinado tamanho
Dada uma matriz arr[] e um número inteiro k encontre a matriz depois de reverter cada submatriz de k elementos consecutivos no lugar. Se o último subarray tiver menos de k elementos, inverta-o como está. Modifique a matriz no local e não retorne nada.
Exemplos:
Entrada: arr[] = [1 2 3 4 5 6 7 8] k = 3
Saída: [3 2 1 6 5 4 8 7]
Explicação: Os elementos são invertidos: [1 2 3] → [3 2 1] [4 5 6] → [6 5 4] e o último grupo [7 8](tamanho < 3) is reversed as [8 7].Entrada: arr[] = [1 2 3 4 5] k = 3
Resultado: [3 2 1 5 4]
Explicação: O primeiro grupo consiste nos elementos 1 2 3. O segundo grupo consiste nos elementos 4 5.EU entrada: arr[] = [5 6 8 9] k = 5
Saída: [9 8 6 5]
Explicação: Como k é maior que o tamanho do array, todo o array é invertido.
[Abordagem ] Reversão de grupo de tamanho fixo
A ideia é considerar cada submatriz de tamanho k começando do início da matriz e invertê-la. Precisamos lidar com alguns casos especiais.
=> Se k não for um múltiplo de n, onde n é o tamanho do array do último grupo, teremos menos de k elementos restantes, precisamos reverter todos os elementos restantes.
=> Se k = 1 o array deve permanecer inalterado. Se k >= n invertemos todos os elementos presentes no array.Para reverter um subarray mantenha dois ponteiros: esquerdo e direito. Agora troque os elementos nos ponteiros esquerdo e direito e aumente para a esquerda em 1 e diminua para a direita em 1. Repita até que os ponteiros esquerdo e direito não se cruzem.
Trabalhando:
C++ #include #include using namespace std ; void reverseInGroups ( vector < int >& arr int k ){ // Get the size of the array int n = arr . size (); 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 -- ]); } } } int main () { vector < int > arr = { 1 2 3 4 5 6 7 8 }; int k = 3 ; reverseInGroups ( arr k ); for ( int num : arr ) cout < < num < < ' ' ; return 0 ; }
C #include void reverseInGroups ( 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 -- ; } } } int main () { int arr [] = { 1 2 3 4 5 6 7 8 }; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ]); reverseInGroups ( arr n k ); for ( int i = 0 ; i < n ; i ++ ) printf ( '%d ' arr [ i ]); return 0 ; }
Java class GfG { static void reverseInGroups ( int [] arr int k ){ int n = arr . length ; for ( int i = 0 ; i < n ; i += k ) { int left = i ; int right = Math . min ( i + k - 1 n - 1 ); // reverse the sub-array while ( left < right ) { int temp = arr [ left ] ; arr [ left ] = arr [ right ] ; arr [ right ] = temp ; left ++ ; right -- ; } } } public static void main ( String [] args ) { int [] arr = { 1 2 3 4 5 6 7 8 }; int k = 3 ; reverseInGroups ( arr k ); for ( int num : arr ) { System . out . print ( num + ' ' ); } } }
Python def reverseInGroups ( arr k ): i = 0 # get the size of the array n = len ( arr ) 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 if __name__ == '__main__' : arr = [ 1 2 3 4 5 6 7 8 ] k = 3 reverseInGroups ( arr k ) print ( ' ' . join ( map ( str arr )))
C# using System ; class GfG { public static void reverseInGroups ( int [] arr int k ){ int n = arr . Length ; 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 ; } } } 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 ; reverseInGroups ( arr k ); for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( arr [ i ] + ' ' ); } } }
JavaScript function reverseInGroups ( arr k ) { let n = arr . length ; 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 ); // reverse the sub-array [left right] while ( left < right ) { // Swap elements [ arr [ left ] arr [ right ]] = [ arr [ right ] arr [ left ]]; left += 1 ; right -= 1 ; } } return arr ; } // Driver Code let arr = [ 1 2 3 4 5 6 7 8 ]; let k = 3 ; let arr1 = reverseInGroups ( arr k ); console . log ( arr1 . join ( ' ' ));
Saída
3 2 1 6 5 4 8 7
Complexidade de tempo: O(n) percorremos todo o array apenas uma vez, invertendo elementos em grupos de tamanho k. Como não revisitamos nenhum elemento, o trabalho total realizado cresce linearmente com o tamanho do array. Portanto, se a matriz tiver n elementos, serão necessárias aproximadamente n etapas.
Espaço Auxiliar: O(1) a reversão é feita diretamente no array original usando apenas algumas variáveis extras.