Leetcode #45. Jump Game II 跳跃游戏2 解题报告

1 解题思想

今天从4点就在赶一个作业,赶死我了。。。被猪队友坑的节奏,赶在12点钱来更新。。更新完继续写作业,好累。还是到Hard的模式,还是简单点说,

这道题还是跳跃游戏,每一位置的取值代表能跳到的最远的位置。这道题不能暴力似乎也不能用原始的DP

简单说解决方法:
用了贪心的策略,reached和times表示跳了times次后,某一段区间内最小的步伐到达数量,而times的计算需要一个上下界,这个可以看我代码的注释,写作业去了

2 原题

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

3 AC解

public class Solution {
    /**
     * http://www.cnblogs.com/ganganloveu/p/3761715.html
     * 我是看了上面那个解析的
     * 
     * times就是跳了多少次
     * reached就是当前跳了times次时能到的最远范围
     * max是路过的位置之处再跳一次能到达的最远的位置
     * 
     * 总之就是用了贪心的策略,reached和times表示跳了times次后,某一段区间内最小的步伐到达数量
     * 
     * 而max则记录了路过的所有节点的,再跳一次能有多远,这个可以用来更新reached
     * 
     * */
    public int jump(int[] nums) {
        int times = 0;
        int reached = 0;
        int max = 0;
        for(int i=0;i< nums.length;i++){
            if(reached < i){
                times++;
                reached = max;
            }
            max = Math.max(max,i+nums[i]);
        }
        return times;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值