首页 > 其他 > 详细

Q45 跳跃游戏 II

时间:2019-05-04 11:53:32      阅读:140      评论:0      收藏:0      [点我收藏+]

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:

输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
     从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
class Solution {
    public int jump(int[] nums) {
        if (nums == null || nums.length <= 1)
            return 0;

        int cur = 0;
        int next = 0;
        int step = 0;

        for (int i = 0; i < nums.length; i++) {
            if (cur < i) {
                step++;
                cur = next;
            }
            next = next > i + nums[i] ? next : i + nums[i];
        }

        return step;
    }
}

Q45 跳跃游戏 II

原文:https://www.cnblogs.com/WeichengDDD/p/10807986.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!