阵列上的左旋转
问题描述:
我有一个问题,我需要在其中旋转数组k次。
I have a question where I need to rotate an array left k times.
即如果k = 2,[1,2,3,4,5]。 -> [3,4,5,1,2]
i.e. if 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 =数组的长度。
where n = length of the array.
我认为问题是映射问题,如果k = 1,则a [0]-> a [n-1]。
I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1.
我的解决方案出了什么问题?
What is wrong with my solution?
答
下面显示了借助索引进行此操作的另一种方法。
Another way to do this with the help of indexing is shown below..
def rotate(l, n):
return l[n:] + l[:n]
print(rotate([1, 2, 3, 4, 5], 2))
#output : [3, 4, 5, 1, 2]
仅当n超出 [-len(l),len(l)]
范围时,才返回原始列表。要使其适用于所有n值,请使用:
This will only return the original list if n is outside the range [-len(l), len(l)]
. To make it work for all values of n, use:
def rotate(l, n):
return l[-n % len(l):] + l[:-n % len(l)]