zoukankan      html  css  js  c++  java
  • LeetCode OJ 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.

    For example:
    A = [2,3,1,1,4], return true.

    A = [3,2,1,0,4], return false.


    【题目分析】

    A[i]的值代表如果到达 i 时可以向前跳的最大步长,判断从i = 0出发是否能到达数组的最后一个值。


    【思路】

    用distance记录当前i之前跳的最远距离。如果distance< i,即代表即使再怎么跳跃也不能到达i。当到达i时,A[i]+i,代表从i能跳最远的距离。max(distance,A[i]+i)代表能到达的最远距离。


    【java代码】

     1 public class Solution {
     2     public boolean canJump(int[] nums) {
     3         if(nums == null || nums.length == 0) return true;
     4         
     5         int distance = 0;
     6         for(int i = 0; i < nums.length && i <= distance; i++){
     7             distance = Math.max(nums[i]+i, distance);
     8         }
     9         return distance < nums.length -1 ? false : true;
    10     }
    11 }
  • 相关阅读:
    Arduino
    DTU
    现代信号处理与应用
    matlab学习记录
    列车准点节能操纵
    泊松过程
    序号生成算法odoo
    操作系统特性
    c语言中的变量
    xml中的四则运算与时间爱格式
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5532408.html
Copyright © 2011-2022 走看看