: 45. Jump Game II
: 給你一個陣列nums,nums[i]表示從這個點可以往後移動幾格,求出從第0格開始,最少
: 跳幾格可以跳到陣列尾端(題目保證一定可以到陣列尾端)。
:
: Example:
:
: Input: nums = [2,3,1,1,4]
: Output: 2
: Explanation: The minimum number of jumps to reach the last index is 2. Jump 1
: step from index 0 to 1, then 3 steps to the last index.
:
: Input: nums = [2,3,0,1,4]
: Output: 2
class Solution:
def jump(self, nums: List[int]) -> int:
count, now_pos = 0, 0
while now_pos < len(nums)-1 :
jump_step = nums[now_pos]
max_length = 0
if now_pos + jump_step >= len(nums)-1 :
return count+1
for i in range(jump_step) :
if nums[now_pos+i+1] == 0 :
continue
else :
max_length_t = nums[now_pos+i+1] + i
if max_length_t > max_length :
max_length = max_length_t
max_i = i+1
now_pos = now_pos + max_i
count += 1
return count
看惹一下別人寫的code
跟我思路一樣可是就是乾淨好多
還有原來可以max()裡面在包for來比
我好爛
QQ