美文网首页
LeetCode 55. Jump Game

LeetCode 55. Jump Game

作者: laiyi_9efc | 来源:发表于2019-01-06 08:59 被阅读0次
  1. 解法1: 遍历
class Solution {
    public boolean canJump(int[] nums) {
        boolean[] result = new boolean[nums.length];
        
        if(nums.length < 2) {
            return true;
        }
        
        result[0] = true;
        for (int i = 0; i < nums.length - 1; i++) {
            if ( result[i] ) {
                int step = nums[i];
                while(step > 0) {
                    int des = i + step;
                    if ( des == nums.length -1 ) {
                        return true;
                    }
                    if ( des < nums.length - 1 ) {
                        result[i+step] = true;
                    }
                    step--;
                }
            }
        }
        return false;
    }
}
  1. 解法2: Greedy
class Solution {
    public boolean canJump(int[] nums) {
        if(nums.length < 2) {
            return true;
        }
        int maxReach = 0;
        for (int i = 0; i < nums.length; i++) {
            if ( maxReach == i && nums[i] == 0 ) {
                return false;
            }
            maxReach = Math.max(maxReach, nums[i] + i);
            if ( maxReach >= nums.length - 1) {
                return true;
            }
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:LeetCode 55. Jump Game

      本文链接:https://www.haomeiwen.com/subject/gjwjrqtx.html