题目描述:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入:[2,3,1,1,4]
输出:2
解释:跳到最后一个位置的最小跳跃数是2。从下标为0跳到下标为1的位置,跳1步,然后跳3步到达数组的最后一个位置。
解题思路:
这是典型的贪心算法,即每次跳都选择能够到达的最远距离,那么跳的次数一定是最少的。
比如 [2,3,4,1,2,1,3,7] :
刚开始步长为2,即在之后的 [3,4] 中选择能够到达的最远距离,所以选4;然后在之后的 [1,2,1,3] 中选择能够到达的最远距离,所以选3 …… 以此类推。
具体代码(Python3):
class Solution():
#判断最远可到达的距离
def max_location(self, new_nums):
max_location = 0
max_length = 0
num = 0
for i in range(len(new_nums)):
location = new_nums[i]+i
if location >= max_location:
max_location = location
max_length = new_nums[i]
num = i
return num+1, max_length
def jump(self, nums):
steps = 0
step_length = nums[0] #最大可跨步长
current_location = 0
if len(nums) != 1:
while True:
if current_location + step_length >= len(nums)-1:
steps += 1
break
new_nums = nums[current_location+1 : current_location+step_length+1]
location, step_length = self.max_location(new_nums)
current_location += location
steps += 1
print(steps)
if __name__ == '__main__':
nums = list(input())
nums = nums[1:len(nums)-1]
nums = ''.join(nums).split(',')
nums = [int(i) for i in nums]
object = Solution()
object.jump(nums)