当前位置:网站首页>Leetcode 45 jump game II

Leetcode 45 jump game II

2022-06-12 01:47:00 baj001

Ideas

Original link

  1. Different from ordinary Jumping Games , This question limits the minimum number of jump steps
  2. Defines the of this jump end Location , It is also the position for the next jump
  3. stay for In circulation ,i To meet the i < length - 1 instead of i < length; Because if i < length It's possible i Is the last position of the array , At this time, the last position of the array is counted , So the function will be out of bounds .
  4. stay for The maximum takeoff position is continuously updated in the cycle , When i == end When , take end to update It is the farthest position you can jump to currently , then steps++
class Solution {
    
    public int jump(int[] nums) {
    
        int length = nums.length;
        int end = 0;//  The right boundary of the reachable range of the last jump ( The next rightmost takeoff point )
        int maxPosition = 0; //  The farthest position you can jump to now 
        int steps = 0; //  The number of jumps 
        // As follows  i < length - 1 Is a key location , Can't make i < length
        for (int i = 0; i < length - 1; i++) {
    
            maxPosition = Math.max(maxPosition, i + nums[i]); 
             //  We have reached the right boundary of the last jump 
            if (i == end) {
    
                 //  The farthest position you can jump to now becomes the right boundary of the next take-off position 
                end = maxPosition;
                //  Go to the next jump 
                steps++;
            }
        }
        return steps;
    }
}
原网站

版权声明
本文为[baj001]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011216128171.html