45. Jump Game II
Medium
3900175Add to ListShare
Given an array of non-negative integers nums
, 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.
You can assume that you can always reach the last index.
Example 1:
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.
Example 2:
Input: nums = [2,3,0,1,4] Output: 2
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 105
我的思路:动态规划
class Solution:
def jump(self, nums: List[int]) -> int:
"""
解题思路:dp[i]表示到i位置所需最小次数
时间复杂度:O(n*m) n为数组长度,m为数组最大步数
空间复杂度:O(n)
"""
dp = [0] * len(nums)
for index, num in enumerate(nums):
for step in range(1, num + 1):
target = index + step
if target >= len(nums):
break
if dp[target] == 0:
dp[target] = dp[index] + 1
else:
dp[target] = min(dp[target], dp[index] + 1)
# print(dp)
return dp[len(nums) - 1]
标准答案: https://leetcode.com/problems/jump-game-ii/solution/
贪心策略思路:当前位置下标 + 当前值 = 能到达的最长距离。所以枚举下标,用贪心尽可能让自己能走到更远的位置,标记起来,当当前位置下标已经是标记的能走的最长位置时,
即耗费了一次次数。意思是之前的一次选择只能到达这个位置了。 时间复杂度:O(n) 空间复杂度:O(1)
class Solution:
def jump(self, nums: List[int]) -> int:
jumps = 0
current_jump_end = 0
farthest = 0
for i in range(len(nums) - 1):
# we continuously find the how far we can reach in the current jump
farthest = max(farthest, i + nums[i])
# if we have come to the end of the current jump,
# we need to make another jump
if i == current_jump_end:
jumps += 1
current_jump_end = farthest
return jumps