LeetCode第55题:跳跃游戏(中等)

LeetCode第55题:跳跃游戏(中等)

  • 题目:给定一个非负整数数组,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个位置。
  • 解法一:根据第45题跳跃游戏改动得到。
class Solution {
    public boolean canJump(int[] nums) {
        int end = 0;
        int maxPosition = 0; 
        boolean ans = false;
        for(int i = 0; i < nums.length - 1; i++){
            maxPosition = Math.max(maxPosition, nums[i] + i); 
            if( i == maxPosition){
                break;
            }
            if( i == end){ 
                end = maxPosition;
            }
        }
        if(end >= nums.length-1) ans = true;
        return ans;
    }
}

在这里插入图片描述

  • 解法二:从最后一位往前找,开始的时候想到了这种做法,没继续思考,没想到这么简单。
public class Solution {
    public boolean canJump(int[] nums) {
        int lastPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/jump-game/solution/tiao-yue-you-xi-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了79 篇原创文章 · 获赞 7 · 访问量 1383

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104144878