Dada una array arr[] y una posición en la array, k. Escriba un nombre de función inversa (a[], k) tal que invierta el subarreglo arr[0..k-1]. El espacio adicional utilizado debe ser O(1) y la complejidad de tiempo debe ser O(k).
Ejemplos:
Input: arr[] = {1, 2, 3, 4, 5, 6} k = 4 Output: arr[] = {4, 3, 2, 1, 5, 6}
Este problema tiene una solución existente, consulte Invierta una array hasta un enlace de posición dado . Resolveremos este problema rápidamente en Python.
# Program to Reverse an array # upto a given position def reverseArrayUptoK(input, k): # reverse list starting from k-1 position # and split remaining list after k # concat both parts and print # input[k-1::-1] --> generate list starting # from k-1 position element till first # element in reverse order print (input[k-1::-1] + input[k:]) # Driver program if __name__ == "__main__": input = [1, 2, 3, 4, 5, 6] k = 4 reverseArrayUptoK(input, k)
Producción:
[4, 3, 2, 1, 5, 6]
Publicación traducida automáticamente
Artículo escrito por Shashank Mishra y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA