阵列上的左旋转 [英] Left Rotation on an Array

查看:113
本文介绍了阵列上的左旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我需要在其中旋转数组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)]

这篇关于阵列上的左旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆