zoukankan      html  css  js  c++  java
  • 跳跃游戏||

    题目链接:https://leetcode-cn.com/problems/jump-game-ii/
    题目描述:

    题解:
    题解参考:
    windliang的题解

    如下图,开始的位置是 2,可跳的范围是橙色的。然后因为 3 可以跳的更远,所以跳到 3 的位置。

    如下图,然后现在的位置就是 3 了,能跳的范围是橙色的,然后因为 4 可以跳的更远,所以下次跳到 4 的位置。

    用end记录能跳的边界,当遍历到边界时,重新更新边界。
    注意:for 循环中,i < nums.length - 1,少了末尾。因为开始的时候边界是第 00 个位置,steps 已经加 11 了。如下图,如果最后一步刚好跳到了末尾,此时 steps 其实不用加 11 了。如果是 i < nums.length,i 遍历到最后的时候,会进入 if 语句中,steps 会多加 11。

    class Solution {
    public:
        int jump(vector<int>& nums) {
            int step = 0;
            int end = 0;
            int cover = 0;
            for(int i = 0; i < nums.size() - 1; i++)
            {
                cover = max(nums[i] + i, cover);
                if(i == end) //遇到边界,更新边界,步数++
                {
                    end = cover;
                    step++;
                }
            }
            return step;
        }
    };
    
  • 相关阅读:
    python--Tuple类型
    python--List类型
    剑指offer--数组中重复的数字
    Assignment HDU
    kuangbin 并查集
    Girls and Boys-hdu 1068
    Computer HDU
    Terrorist’s destroy HDU
    Roads in the North POJ
    Labyrinth POJ
  • 原文地址:https://www.cnblogs.com/ZigHello/p/14874975.html
Copyright © 2011-2022 走看看