45. Jump Game II

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值