55. Jump Game

    xiaoxiao2025-02-28  18

    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.

    Determine if you are able to reach the last index.

    For example: A = [2,3,1,1,4], return true.

    A = [3,2,1,0,4], return false.

    判断能否跳跃,从后往前判断  主要问题出现在0    如果当前为出现0那么它的前面的数必须大到足够跳过这一位, 需要注意[4,1,0,0,3]类似的情况 4时可以直接跳到最后了

    public class Solution { public boolean canJump(int[] nums) { int cnt=0; for(int i=nums.length-2;i>=0;i--){ if(nums[i]<=cnt) cnt++; else { cnt=0; } } return cnt==0; } }

    从前往后判断 觉得这才是最应该用的解法

    public class Solution { public boolean canJump(int[] nums) { if(nums == null || nums.length == 0) return false; int maxCover = 0; for(int i = 0; i < nums.length && i <= maxCover; i++) { maxCover = Math.max(nums[i] + i, maxCover); if(maxCover >= nums.length - 1) return true; } return false; } }

    转载请注明原文地址: https://ju.6miu.com/read-1296751.html
    最新回复(0)