Leetcode题解:Jump Game

原题:https://leetcode.com/problems/jump-game/description/
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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.

这道题要我们判断能否按照规定的跳转规则,从数组的第一个元素跳到最后一个元素。我们可以不用去找出一条特定的跳转路径,只需要不断迭代算出当前最远能够跳转到哪一个元素。

这里可以使用贪心策略,每次迭代都计算出当前能够跳到最远的位置。通过多次迭代直到能够到达的范围包含了最后一个元素。如以下算法所示:

// golang 12ms (runtime beats 100%)
func canJump(nums []int) bool {
	max := nums[0] + 1
	for i := 0; i < max; i++ {
		if i + nums[i] + 1 > max {
			max = i + nums[i] + 1
		}
		if max >= len(nums) {
			return true
		}
	}
	return false
}

上面这个算法是从数组第一个元素开始跳转的。从另一个角度想,我们也可以从最后一个元素开始进行倒推,往前遍历(即下标减小的方向)寻找第一个能够到达该元素的元素。重复该过程即可不断逼近数组的第一个元素。算法如下:

// golang 12ms (runtime beats 100%)
func canJump(nums []int) bool {
    if len(nums) == 1 {
        return true
    }
    curPos := len(nums) - 1
    var nearestLastPos int 
    for ;curPos > 0; {
        nearestLastPos = curPos
        for i := curPos - 1;i >= 0;i-- {
            if nums[i] >= curPos - i {
                nearestLastPos = i
                break
            }
        }
        if bestLastPos == curPos {
            return false
        }
        curPos = bestLastPos
    }
    return true
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值