leetcode 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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

中文理解:

给定一个数组,假设总是能够走到最后最后一个下标的位置,求出需要走的最短的步数。

解题思路:

使用贪心法,不过是从最后的一个下标逆向寻找距离这个下标最远的点,然后更新这个最远的点为最后一步的下标,再同样策略贪心,最后得到需要走的最少的步数。

代码(java):

class Solution {
    public int jump(int[] nums) {
        if(nums==null||nums.length<2)
            return 0;
        int count = 0;
        int curr=nums.length-1;
        while(curr!=0){
            for(int i = 0;i<curr;i++){
                if(i+nums[i]>=curr){
                    count++;
                    curr=i;
                }
            }
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/90171647