找规律-跳跃游戏

2024-07-19  本文已影响0人  今夜秋风和

跳跃游戏

https://leetcode.cn/problems/jump-game/description/

题目分析

nums = [2,3,1,1,4]
当前位置array[i]表示基于当前位置可以跳的最大步数, 例如:从当前index=0 位置,可以跳的步数为1步,2步,跳1步到index=1位置, 跳2步到index=2位置; 继续遍历index = 1 位置, 而index=1 位置是通过index= 0 通过跳1步过来的,对于按最大步数跳2步来说,index = 1位置是从index= 0 位置必达的,所以,我们只需要维护按照最大步数跳的最大索引就行;
跳转的最大索引maxIndex表示为基于当前索引和可以跳转的最大步数之和, 当 index = 0 位置,maxIndex = 2,对于index=1 位置,当前可以跳转的最大索引为maxIndex= 1+3=4,于是,在遍历的过程中通过动态维护最大索引,当maxIndex >= array.length-1时,即认为可以跳转到;

编程实现

    public boolean canJump(int[] nums) {
        if(nums == null || nums.length <= 0){
            return false;
        }
        int maxIndex = 0;
        for(int index = 0; index< nums.length;index++){
            if(index <= maxIndex){
                if(index + nums[index] > maxIndex){
                    maxIndex = index + nums[index];
                }
                if(maxIndex >= nums.length -1){
                    return true;
                }
            }
        }
        return false;

    }
上一篇 下一篇

猜你喜欢

热点阅读