45. 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.)

 

Hide Tags
  Array Greedy  

链接: http://leetcode.com/problems/jump-game-ii/

题解:

在Jump Game基础上还要计算最小jump数,所以除了maxCover外还需要维护一个lastCover。在当前i值超过lastCover所处index时,我们要把steps数加1。在循环结束后再判断是否满足能到达最后一个index,假如可以,返回steps,不可以则返回0。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public int jump(int[] nums) {

        if(nums == null || nums.length == 0)

            return 0;

        int maxCover = 0, lastCover = 0, steps = 0;

        

        for(int i = 0; i < nums.length && i <= maxCover; i++){

            if(i > lastCover){

                steps++;

                lastCover = maxCover;

            }

            if(i + nums[i] > maxCover)

                maxCover = i + nums[i];

        }

        

        if(maxCover >= nums.length - 1)                

            return steps;

        return 0;

    }

}

 

测试:

你可能感兴趣的:(game)