首页 > 其他 > 详细

LeetCode OJ 55. Jump Game

时间:2016-05-26 20:25:43      阅读:156      评论:0      收藏:0      [点我收藏+]

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 }

 

LeetCode OJ 55. Jump Game

原文:http://www.cnblogs.com/liujinhong/p/5532408.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!