您的位置:首页 > 编程语言 > Java开发

leetcode:Jump Game II 【Java】

2016-03-05 23:04 513 查看
一、问题描述

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.
二、问题分析

利用贪心法,尝试每步都跳到最远。

三、算法代码

public class Solution {
    public int jump(int[] nums) {
        //贪心法
        
        //当只有一阶台阶时,不需要跳,所以所需步数为0
        if(nums.length == 1){
            return 0;
        }
        
        int step = 0;//当前已经跳的步数
        int left = 0;
        int right = 0;//[left, right]为当前可以跳到的台阶区域
        
        while(left <= right){ //尝试从每一层跳到最远
            step++;
            int old_right = right;
            for(int i = left; i <= old_right; i++){//从当前可以跳到的区域中再次起跳,看能否到达最后的台阶
                int new_right = i + nums[i];
                if(new_right >= nums.length - 1){
                    return step;
                }
                if(new_right > right){
                    right = new_right;
                }
            }
            //当前可以跳到的区域已经搜索完毕,构造下一个起跳区域的起始台阶
            left = old_right + 1;
        }
        return 0;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: