[leetcode] 45.Jump Game II

Jump Game II

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.

Your goal is to reach the last index in the minimum number of jumps.

For example: Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step
from index 0 to 1, then 3 steps to the last index.)

Note: You can assume that you can always reach the last index.

Logic

Update an element locating a reachable position and record next maximum reachable position for update.

Time Complexity

O(n)

Space Complexity

O(1)

Code

public class Solution {
    public int jump(int[] nums) {
        int len = nums.length;
        int maxstep = 0;
        int cur = 0;
        int count = 0;
        for(int i=0; i<len; i++){
            if(cur<i){
              count++;
              cur = maxstep;
            }
            
            maxstep = Math.max(maxstep, nums[i]+i);
        }
        return count;
    }
}
阅读 1.2k

推荐阅读
pawn
用户专栏

算法,前端起步,记录学习过程

0 人关注
4 篇文章
专栏主页