原题:
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.
Example:
Input: [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.
大致意思是:列表已给出在每个位置最多能移动的长度,从列表头部出发,最少经过多少步到达列表尾部。
一开始想到的是动态规划:
class Solution:
def jump(self, nums):
n = len(nums)
if n == 1:
return 0
steps = [n] * n
steps[n-1] = 0
for i in range(n-2, -1, -1):
step = nums[i]
if step+i < n:
steps[i] = min(steps[i:i+step+1])+1
else:
steps[i] = min(steps[i:n-1])+1
return steps[0]
结果发现Time Limit Exceeded,也就是说,我们的算法时间复杂度O(n^2)较高。因此我们尝试一下其他的算法,参考了他人的代码后,发现可以使用BFS和贪心算法。我们这里使用贪心算法,计算从列表头能够到达的最远距离:
class Solution:
def jump(self, nums):
n = len(nums)
step = 0 #step代表步数
m = 0 #m代表从nums[0]能到达的最远距离
x = 0 #x代表在step步能走的最远距离
for i in range(n-1):
m = max(nums[i]+i, m) #计算从nums[0]能到达的最远距离
if i == x:
step += 1
x = m
return step