美文网首页
45. Jump Game II

45. Jump Game II

作者: RobotBerry | 来源:发表于2017-05-02 16:31 被阅读0次

    问题

    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.

    例子

    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.

    分析

    首先考虑dp,空间复杂度为O(n),时间复杂度为O(n^2),超时;
    再考虑bfs,先列出从起点出发能跳到的节点,再列出从这些节点出发能跳到的节点......直到跳到终点。记录bfs的层数。

    要点

    dp/dfs

    时间复杂度

    O(n)

    空间复杂度

    O(1)

    代码

    class Solution {
    public:
        int jump(vector<int>& nums) {
            if (nums.size() < 2) return 0;
            // i:数组下标 level: bfs层数
            // curRange: 当前能跳到的最远范围
            // nextRange: 下一步能跳到的最远范围
            int i = 0, level = 0, curRange = 0, nextRange = 0;
            while (i <= curRange) {
                level++;
                for (; i <= curRange; i++) {
                    nextRange = max(nextRange, i + nums[i]);
                    if (nextRange >= nums.size() - 1) return level;
                }
                curRange = nextRange;
            }
            return 0;
        }
    };
    

    扩展

    如果问题中数组的元素表示只能跳的步数(原题目为能跳的最大步数),那么可能会有一些节点会跳不到,但还可以用bfs在O(n)时间内解决。

    相关文章

      网友评论

          本文标题:45. Jump Game II

          本文链接:https://www.haomeiwen.com/subject/nsoctxtx.html