Skip to main content
 首页 » 编程设计

python之圆阵旋转的高效算法-python

2025年05月04日19fff_TT

对于给定的数组,我想执行多次右旋。例如给定数组[1, 2, 3],旋转数为2,我想得到[2, 3, 1]。

为此,我用 Python 编写了下面给出的代码。我还研究了 here 中给出的解决方案.但是,我正在寻找一种优雅的算法,可以使用 Python 中的 native 数据结构更有效地执行它。

这是我的代码:

def circularArrayRotation(a, k): 
    for i in range(k): 
        temp = [0]*len(a) 
        for j in range(len(a)-1): 
            temp[j+1] = a[j] 
        temp[0] = a[len(a)-1] 
        a = temp 
a = [1,2,3] 
k = 2 

请您参考如下方法:

你可以使用这个技巧:

l = [1, 2, 3] 
number_of_rotations = int(input()) 
number_of_rotations = number_of_rotations % len(l)  
 
rotated = l[number_of_rotations-1:] + l[:number_of_rotations-1] 
print(rotated) 

请看第 3 行的技巧。如果我们按列表的长度旋转列表的次数,那么我们将取回原始列表。这就是为什么我们不需要这样做。我们将轮换实际有效的时间。