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;
        }
    };
  • 相关阅读:
    用List绑定GridView的简单辅助类
    宋忠玲(帮读者名字作诗)
    [转帖]每天看一遍,释怀所有难过
    30岁,我们怎么赢?
    柴门远望
    创业,不要被那些成功人士所忽悠
    一只海燕飞过来
    成功者都在用的“成功咒语”
    诗歌复兴
    游熊猫基地有感
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12783651.html
Copyright © 2011-2022 走看看