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 }
原文地址:https://www.cnblogs.com/liujinhong/p/5532408.html