Leetcode之Jump Game & Jump Game II

Jump Game题目描述如下:

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

对于题目一,思路很简单,贪心,只需要时刻计算前位置和当前位置所能跳的最远长度,并始终和n作比较就可以:

1,若在任意位置出现max(表示当前能跳到的最远范围) <= index 且 当前值为0,则说明无法继续向前移动,返回false

2.若在任意位置出现index + nums[index] > max,则说明能跳到更远的位置,更新max值;

3.若max >= len(nums) - 1, 说明可以完成最后一跳,返回true

Python代码如下:

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        
        if nums == None or len(nums) <= 1:
            return True
        
        max = nums[0]
        for i in range(len(nums)):
            if max <= i and nums[i] == 0:
                return False
            if i + nums[i] > max:
                max = i + nums[i]
            if max >= len(nums) - 1:
                return True
        return False

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.

For example:
Given array A = [2,3,1,1,4]

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.)

即在Jump Game的基础上,我们要求出跳到终点的最小步数,我们可以维护一个区间,表示当前跳能达到的位置范围。 递推的方法为:每次都遍历一遍当前区间内的所有元素,从一个元素出发的最远可达距离是 index+array[index] ,那么下一个区间的左端点就是当前区间的右端点+1,下一个区间的右端点就是当前区间的 max(index+array[index]) ,以此类推,直到区间包含了终点,统计当前步数即可。

Python代码如下:

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if nums == None or len(nums) == 1:
            return 0
        
        begin = 0
        end = 0
        max_index = 0
        count = 0
        
        while max_index < len(nums) - 1:
            count += 1
            for i in range(begin, end + 1):
                max_index = max(max_index, i + nums[i])
            begin = end + 1
            end = max_index
        return count
            
        
以上内容参考 http://blog.csdn.net/loverooney/article/details/38455475

https://segmentfault.com/a/1190000002651263

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值