贝壳w

给定一个正整数数组,最大为100个成员,从第一个成员开始,走到数组最后一个成员最少的步骤数,第一步必须从第一个元素开始,1<=步长<len/2,第二步开始以所在成员的数字走相应的步数,如果目标不可达返回-1,只输出最少的步骤数量

题目内容:给定一个正整数数组,最大为100个成员,从第一个成员开始,走到数组最后一个成员最少的步骤数,第一步必须从第一个元素开始,1<=步长<len/2,第二步开始以所在成员的数字走相应的步数,如果目标不可达返回-1,只输出最少的步骤数量。

输入:由正整数组成的数组,以空格分隔,数组长度小于100,请自行解析数据数量。
输出:正整数,表示最少的步数,如果不存在输出-1。

python代码:

'''在步长限制范围内,通过迭代更新当前的索引及下一步的步长'''
#
num_arr = input().split(' ') #num_arr = [int(i) for i in num_arr] num_arr = [7,5,9,4,2,6,8,3,5,4,3,9] # 示例 ,输出为2 N = len(num_arr) if N%2==0: max_step_length = N/2-1 else: max_step_length = N/2 num_list = [] for step in range(1,int(max_step_length)): index_next = step num = 1 while index_next<N: next_step = num_arr[index_next] index_next = index_next + next_step if index_next<N: num+=1 if index_next == N-1: num_list.append(num) # print("step:",step) # print("num_list:",num_list) if index_next>=N: num_list.append(-1) out_num = [ i for i in num_list if i>0] if len(out_num)==0: print(-1) else: print(min(out_num))

代码通过率80%, 记录笔试所遇问题,待解决,如有大佬帮忙指正,感激不尽!

posted on 2020-04-11 20:57  贝壳w  阅读(2649)  评论(0编辑  收藏  举报

导航