Leetcode 45. Jump Game II

原题:

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值