[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.3k

pawn
算法,前端起步,记录学习过程
1 声望
0 粉丝
0 条评论
1 声望
0 粉丝
宣传栏