Problem
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Algorithm
Greedy is good. The sum of position and the max jump length is the selection criteria.
Code
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num_len = len(nums)
if num_len < 2:
return 0
if nums[0] >= num_len-1:
return 1
end = nums[0]
ans = 1
new_end = end
for i in range(1, num_len-1):
if i <= end:
if new_end < i + nums[i]:
new_end = i + nums[i]
if i == end:
end = new_end
ans += 1
return ans
小白菜又菜
发布了1248 篇原创文章 · 获赞 199 · 访问量 116万+
关注