zoukankan      html  css  js  c++  java
  • [leetcode]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.

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

    题意:

    思路:

    以 [2,3,1,1,4]为例

    可以想象一只青蛙,在每个刻度的石头上,弹跳力分别为2,3,1,1,4。青蛙是否能安全过河。

    用maxReachIdx记录当前能跳的最远距离

    指针i边扫边更新maxReachIdx

    若maxReachIdx >= nums.length - 1 则返回true。

    例子走一遍,先初始化指针 i= 0 , maxReachIdx = 0

    当 i = 0 时,进入for循环,maxReachIdx更新为 3, 可以把红色部分看为青蛙可跳的势力范围

    当 i = 4,  maxReachIdx仍然为 3 则maxReachIdx  < nums.length - 1 返回false 。

    代码:

    1   public boolean canJump(int[] nums) {
    2         int maxReachIdx = 0;
    3         for (int i = 0; i < nums.length && i <= maxReachIdx; i++){
    4             maxReachIdx = Math.max(maxReachIdx,  i + nums[i]);
    5         }
    6         return maxReachIdx >= nums.length - 1;
    7     }
  • 相关阅读:
    算法训练 区间k大数查询
    算法训练 最大最小公倍数
    身份证号码升级
    python包与模块导入
    python函数
    HDU 3595 博弈论,被支配的恐惧
    BZOJ 3195 [Jxoi2012]奇怪的道路
    大暑假集训
    [Poi2010]Monotonicity 2
    BZOJ 4868 HEOI 期末考试
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9136872.html
Copyright © 2011-2022 走看看