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

[leetcode]Jump Game

时间:2014-08-08 01:52:15      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   for   ar   

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.

算法思路:

维护一个一位数组canAccess,canAccess[i]表示第i点是可达的。初始化canAccess[0] = true;同时,维护一个指针,指向最远可达距离。以免重复计算;

遍历数组A,没遇到一个元素,就更新canAccess数组,当遍历到某个A中的元素不可达时,跳出循环。

代码如下:

 1 public class Solution {
 2     public boolean canJump(int[] a) {
 3         if (a == null || a.length < 2)
 4             return true;
 5         boolean[] canAccess = new boolean[a.length];
 6         canAccess[0] = true;
 7         int approach = 0;
 8         for (int i = 0; i < a.length; i++) {
 9             if (!canAccess[i]) break;
10             if (i + a[i] <= approach)//该元素无需再处理
11                 continue;
12             for (int j = approach; j <= i + a[i]; j++) {
13                 if (j == a.length - 1)//若达终点,直接返回
14                     return true;
15                 canAccess[j] = true;
16             }
17             approach = i + a[i] ;//记录最远可达点
18         }
19         return canAccess[a.length - 1];
20     }
21 }

 

[leetcode]Jump Game,布布扣,bubuko.com

[leetcode]Jump Game

标签:style   blog   http   color   os   io   for   ar   

原文地址:http://www.cnblogs.com/huntfor/p/3898452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!