Jumping Game - Algorithm - Simple and easy to understand solution

Jumping Game I:

question:

Given an array nums of non-negative integers, you are initially at the first index of the array. Each element in the array represents the maximum length you can jump at that position. Determine whether you can reach the last subscript.

Example 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: You can jump 1 step first, from subscript 0 to subscript 1, and then jump 3 steps from subscript 1 to the last subscript.

Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: No matter what, the position with subscript 3 will always be reached. But the maximum jump length of this subscript is 0, so it is never possible to reach the last subscript.

Simple and understandable solution:

In the process of jumping, the most deadly element value is 0. If you cannot jump over an element with a value of 0, you will be stuck. We need a variable to continuously update the farthest subscript that can be jumped to. If this subscript is equal to or greater than the last subscript of the array, it means that we can jump to the end; if the farthest subscript that can be jumped to is stuck At the position where the element value is 0, and this element is not the last element, then it is really stuck and returns false directly.
insert image description here

class Solution {
    
    
    /**
        最关键的元素值是0,如果最远的距离只能卡到0的位置,那么必然被卡住
     */
    public boolean canJump(int[] nums) {
    
    
        int f = 0;
        for (int i = 0; i < nums.length; i++) {
    
    
            // 不断更新能跳到的最远下标
            f = Math.max(f, i + nums[i]);
            // 如果最大的能跳到的距离只能落在值0,并且值0不是最后的元素,那么必然被卡住
            if (nums[i] == 0 && f == i && i != nums.length-1) {
    
    
                return false;
            }
        }
        return true;
    }
}

Jumping Game II:

Guess you like

Origin blog.csdn.net/Xidian2850/article/details/123785741