难度指数:⭐⭐⭐⭐
def min_step(nums):res = float("inf")len_arr = len(nums)len_step = len(nums)//2+1for i in range(1,len_step):step = 1 arr_index = iwhile (1):arr_index += int(nums[arr_index])step += 1 if arr_index > len_arr - 1:breakif arr_index == len_arr - 1:res = min(res,step)break if (res == float("inf")):return -1else:return res
普遍算法:
idea:
def min_step0(nums):N=len(nums)temp=1begin_p=(N-1)//2end_ps=[N-1]while(len(end_ps)):valid=[]for n in end_ps:for i in range(1,n):if (i+nums[i]==n):if i<=begin_p:temp+=1return tempvalid.append(i)temp+=1if len(valid)==0:temp=-1end_ps=valid return temp
耗时对比:
from time import time
T=10
while T:nums=[random.randint(1,100) for _ in range(1,random.randint(1,100))]t1=time()print(min_step(nums))t2=time()print(min_step0(nums))t3=time()print(t2-t1,t3-t2)T-=1
完整代码如下:
import random
def min_step(nums):res = float("inf")len_arr = len(nums)len_step = len(nums)//2+1for i in range(1,len_step):step = 1 arr_index = iwhile (1):arr_index += int(nums[arr_index])step += 1 if arr_index > len_arr - 1:breakif arr_index == len_arr - 1:res = min(res,step)break if (res == float("inf")):return -1else:return resdef min_step0(nums):N=len(nums)temp=1begin_p=(N-1)//2end_ps=[N-1]while(len(end_ps)):valid=[]for n in end_ps:for i in range(1,n):if (i+nums[i]==n):if i<=begin_p:temp+=1return tempvalid.append(i)temp+=1if len(valid)==0:temp=-1end_ps=valid return tempT=10
while T:nums=[random.randint(1,100) for _ in range(1,random.randint(1,100))]print(min_step(nums))print(min_step0(nums))T-=1
本文发布于:2024-01-28 16:32:19,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064307428751.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |