码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 55. Jump Game

时间:2016-05-26 20:26:46      阅读:123      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!