LeetCode刷题笔记-45

LeetCode-45. Jump Game II(Hard):

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.

Note:

You can assume that you can always reach the last index.

我的解法:

由于是Hard题,所以我事先查了下这道题的思路,大神都说用贪心算法。

查了一下贪心算法,据说可以用贪心算法的都可以用动态规划做,区别就在于动态规划要求找出所有子问题的解,子问题的解也一定是整个问题的最优解,然后通过递推最后得到最终解;而贪心算法则是在每一个子问题中总是以最理想的解为解,当然理想解不一定是整个问题的最优解。

这道题用贪心算法:首先就贪心的想,能不能一步就到终点,发现不能就想能不能两步到终点。。。总是尝试以最少的步数努力到终点。

自己尝试写了下逻辑有点混乱钻到死胡同了。。。还是找了大神的代码,下面的代码很精妙,大体思路是,从nums的第一位开始遍历位置,利用nextreach(随着位置前移不断更新到最远距离)记录从当前位置再跳两步可以到达的最远位置,利用reach记录当前位置跳一步能到达的最远位置,然后循环i往下走,如果没走到之前记录的跳一步能到达的最远位置,就比较看如果循环到当前位置再走一步是不是能到终点,能就返回step+1,不能就再往下走;如果走到了之前记录的跳一步最远位置reach结果还没到终点,说明当前step肯定到不了,就step++,然后把reach改成上一个位置跳两步能到达的最远位置也就是nextreach(由于step+1并且位置前移了,所以reach记录的还是当前位置跳一步能到达的最远位置)

class Solution {
    public int jump(int[] nums) {
        if(nums.length == 1) return 0;
        int reach = 0;
        int nextreach = nums[0];
        int step = 0;
        for(int i = 0;i < nums.length;i++){
            nextreach = Math.max(i+nums[i],nextreach);
            if(nextreach >= nums.length-1) return (step+1);
            if(i == reach){  //这个最关键,因为reach为之前所能达到的最远距离
                step++;
                reach = nextreach;
            }
        }
        return step;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值