zoukankan      html  css  js  c++  java
  • 55. Jump Game

    题目描述

    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.

    Determine if you are able to reach the last index.

    Example1

    Input: [2,3,1,1,4]
    Output: true
    Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

    Example2

    Input: [3,2,1,0,4]
    Output: false
    Explanation: You will always arrive at index 3 no matter what. Its maximum
                jump length is 0, which makes it impossible to reach the last index.

    难度系数

    Medium

    解法:每到一个节点,计算当前所能走的最远距离;

    class Solution {
    public:
        bool canJump(vector<int>& nums) {
            int size = nums.size();
            int step = nums[0];
            for (int i = 1; i<size; ++i){
                step--;
                //如果以下条件成立,则i-1的位置必然为0
                if (step<0)
                    return false;
                //nums[i]表示当前位置可以向前走的距离
                //step表示到达i时,还能向前走多远;
                //最后选两者较大的指,就是当前位置能向前走的最远的距离
                if (nums[i]>step)
                    step = nums[i];
                //运行到这,最远的距离就是i+step,已经包含了之前所有能走的最远距离
            }
            return true;
        }
    };
  • 相关阅读:
    设计模式
    刷新所有视图存储过程
    js杨辉三角控制台输出
    2018申请淘宝客AppKey
    w3c标准 dom对象 事件冒泡和事件捕获
    promise原理
    vue virtual Dom
    css学习
    seo优化
    新概念学习
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12783651.html
Copyright © 2011-2022 走看看