【发布时间】:2020-03-01 00:24:25
【问题描述】:
在 JAVA 中提出了类似的问题,但有人可以帮助我改进代码:并解释我的代码的时间复杂度和空间复杂度是多少。我的代码检查两个数组是否相互旋转:
list1 = [1, 2, 3, 4, 5, 6, 7]
list2b = [4, 5, 6, 7, 1, 2, 3]
is_rotation(list1, list2b) 应该返回 True。
list2c = [4, 5, 6, 9, 1, 2, 3]
is_rotation(list1, list2c) 应该返回 False。
我的代码:
def is_rotation (list1,list2):
i = 0
j = 0
k = 0
result = True
if len(list1) != len(list2):
return False
while i < len(list1) -1 and j < len(list1) -1:
if list1[i] == list2[j]:
i = i +1
j = j +1
break
elif list1[i] > list2[j]:
j = j +1
else:
i = i +1
else:
return False
for l in range(i,len(list1)):
if i == j:
if list1[i] != list2[j]:
return False
elif list1[i] != list2[j] or list2[i] != list1[k]:
return False
else:
i = i +1
j = j +1
k = k +1
return result
【问题讨论】:
-
一些 cmets 来描述循环应该完成的任务会有所帮助
-
如果值是唯一的,请考虑以下简化:i2 = l2 中 l1[0] 的索引;旋转 iff,对于 x in 0 到 len l1,其中 l1[x] == l2[(i2 + x) % len l1] - 可以写成两个简单的循环(或更少)。也就是说,使用一组唯一的值,它只是比较给定先前选择的第二个列表开始的“偏差”的序列相等性。
-
可以通过尝试将 l2 中所有出现的 l1[0] 作为“偏差”,直到一个匹配,修改上述内容以使用非唯一值。
-
一种快速的方法,O(n),是使用一些快速算法进行精确的字符串匹配,如 Knuth-Morris-Pratt,但应用于列表项而不是字母。跨度>
-
一个简单的方法是查看所有可能的旋转。列表
a通过k位置的轮换只是a[k:] + a[:k]。
标签: python python-3.x algorithm