美文网首页
45.跳跃游戏II

45.跳跃游戏II

作者: HITZGD | 来源:发表于2018-12-12 10:33 被阅读0次

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

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

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

    示例:

    输入: [2,3,1,1,4]
    输出: 2
    解释: 跳到最后一个位置的最小跳跃数是 2。
    从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

    说明:假设你总是可以到达数组的最后一个位置。

    思路
    记录在n步能走的最远距离maxpos,当超越最远距离则,n=n+1,依此循环即可求解,具体代码如上,下面讲一下具体逻辑

    (1)step记录步数

    (2)lastpos记录step步数时,能走的最远距离

    (3)maxpos记录当前位置i能走的最远距离,为原maxpos和i+nums[i]的最大值

    (4)当位置i超越step能走的lastpos距离时,则需要增加一步step+=1,并更新此步能走的最远距离lastpos=maxpos

    #include <vector>
    #include <algorithm>
    using namespace std;
    class Solution {
    public:
        int jump(vector<int>& nums) {
            int step = 0, lastPos = 0, maxPos = 0;
            for (int i = 0; i < nums.size(); i++)
            {
                if (i > lastPos)
                {
                    lastPos = maxPos;
                    step += 1;
                }
                maxPos = max(maxPos, i + nums[i]);
            }
            return step;
        }
    };
    
    int main(int argc, char* argv[])
    {
        vector<int> test = { 2,3,1,1,4 };
        auto res = Solution().jump(test);
        return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:45.跳跃游戏II

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