【LeetCode】 45. Jump Game II 跳跃游戏 II(Hard)(JAVA)

【LeetCode】 45. Jump Game II 跳跃游戏 II(Hard)(JAVA)

题目地址: https://leetcode.com/problems/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.

题目大意

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

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

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

解题方法

1、当前 i 最远可以到达的地方:i + nums[i]
2、当前范围内,最远可以到达记录在 longest 里面
3、如果超过了 last,就需要 +1 次,因为需要在某个地方跳一次

class Solution {
    public int jump(int[] nums) {
        int res = 0;
        int last = 0;
        int longest = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > last) {
                last = longest;
                res++;
            }
            longest = (i + nums[i]) > longest ? i + nums[i] : longest;
        }
        return res;
    }
}

执行用时 : 1 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 40.6 MB, 在所有 Java 提交中击败了 7.88% 的用户

发布了81 篇原创文章 · 获赞 6 · 访问量 2298

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104753195