在数组中找到运行
行程定义为三个或三个以上的数字,它们以恒定的步长从上一个数字开始递增。例如,[1,2,3]是带有步骤1的运行,[1,3,5,7]是带有步骤2的运行,而[1,2,4,5]不是运行。
我们可以用符号“ i到j由s”表示这些运行,其中i是运行的第一个数字,j是运行的最后一个数字,而s是步骤。但是,步骤1的运行将表示为“ i至j”。
因此,使用之前的数组,我们得到:
[1,2,3]->“ 1to3”
[1,3,5,7]->“ 1to7by2”
[1,2,4,5]->“ 1 2 4 5”
在这个挑战中,您的任务是对可能多次运行的阵列执行此操作。
具有递归的示例Python代码:
def arr_comp_rec(a, start_index):
# Early exit and recursion end point
if start_index == len(a)-1:
return str(a[-1])
elif start_index == len(a):
return ''
# Keep track of first delta to compare while searching
first_delta = a[start_index+1] - a[start_index]
last = True
for i in range(start_index, len(a)-1):
delta = a[i+1] - a[i]
if delta != first_delta:
last = False
break
# If it ran through the for loop, we need to make sure it gets the last value
if last: i += 1
if i - start_index > 1:
# There is more than 2 numbers between the indexes
if first_delta == 1:
# We don't need by if step = 1
return "{}to{} ".format(a[start_index], a[i]) + arr_comp_rec(a, i+1)
else:
return "{}to{}by{} ".format(a[start_index], a[i], first_delta) + arr_comp_rec(a, i+1)
else:
# There is only one number we can return
return "{} ".format(a[start_index]) + arr_comp_rec(a, i)
输入值
正整数排序数组(无重复)
输出量
运行的字符串用空格或运行的字符串数组分隔
不需要在特定方向上贪婪
可以有尾随空格
测试用例
In: [1000, 1002, 1004, 1006, 1008, 1010]
Out: "1000to1010by2"
In: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
Out: "1to3 5 8 13 21 34 55 89 144 233"
In: [10, 20, 30, 40, 60]
Out: "10to40by10 60"
In: [5, 6, 8, 11, 15, 16, 17]
Out: "5 6 8 11 15to17"
In: [1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 30, 45, 50, 60, 70, 80, 90, 91, 93]
Out: "1to7 9to15by2 30 45 50to90by10 91 93"
这是代码高尔夫球,因此赢得的字节数最少。
[4, 5, 6, 7, 9, 11, 13, 15]
不能4to6 7to15by2
吗?)