我有一个问题,我需要将一个数组向左旋转k次。
即如果k= 2,1,2,3,4,5。-> 3、4、5、1、2
所以,我的代码是:
def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t
return a其中n=数组的长度。
我认为问题是一个映射问题,如果k= 1,则是一个-> an-1。
我的解决方案有什么问题?
发布于 2021-08-27 03:18:06
def rotateLeft(rotation, arr):
res = [None] * len(arr)
rotation = rotation % len(arr)
for i in range(0, len(arr)):
index = i - rotation
if index < 0:
index = index + len(arr)
res[index] = arr[i]
return res或
def rotateLeft(rotation, arr):
return arr[rotation:] + arr[:rotationhttps://stackoverflow.com/questions/49462195
复制相似问题