배열 내에서 런 찾기
런은 이전 단계에서 일정한 단계로 증가하는 3 개 이상의 숫자로 정의됩니다. 예를 들어 [1,2,3]은 1 단계에서 실행되고 [1,3,5,7]은 2 단계에서 실행되며 [1,2,4,5]는 실행이 아닙니다.
이 런을 "i to j by s"표기법으로 표현할 수 있습니다. 여기서 i는 첫 번째 런 수이고, j는 마지막 런 수이며 s는 단계입니다. 그러나, 단계 1의 실행은 "i 내지 j"로 표현 될 것이다.
따라서 이전에 배열을 사용하면 다음을 얻습니다.
[1,2,3]-> "1to3"
[1,3,5,7]-> "1to7by2"
[1,2,4,5]-> "12 25"
이 문제에서는 여러 번 실행할 수있는 어레이에 대해이 작업을 수행해야합니다.
재귀가있는 예제 파이썬 코드 :
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)