leetcode55——跳跃游戏——java实现

题目要求:
leetcode55——跳跃游戏——java实现_第1张图片
分析:
这道题目利用贪心算法的思想来做会比较简单。
关于贪心算法,可以大致看一下这位大神写的博客:算法(六):图解贪婪算法
对于本题,我们应该这样思考:
定义一个变量temp,用其来表示它能跳得最远的距离:

  1. 当temp的值与该数组的长度相等,或者比该数组的长度大时,就证明它里面肯定存在至少一种跳法,能够刚好跳到最后一步;
  2. 当temp的值比遍历到的i的值要小时,就证明它跳不到最后一步。

具体代码如下:

class Solution {
    public boolean canJump(int[] nums) {
        //贪心算法
        int temp = 0;
        for(int i = 0; i < nums.length; i++) {
            temp = Math.max(nums[i] + i, temp);
            if(temp >= nums.length - 1) {
                return true;
            }
            if(temp <= i) {
                return false;
            }
        }
        return false;
    }
}

你可能感兴趣的:(leecode)