[Leetcode] 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.

 

记录当前所能达到的最远处,与给定的终点比较。

 

 1 class Solution {
 2 public:
 3     bool canJump(int A[], int n) {
 4         int reach = 0;
 5         for (int i = 0; i < n; ++i) {
 6             if (i <= reach) {
 7                 reach = (i + A[i]) > reach ? (i + A[i]) : reach;
 8             } else {
 9                 return false;
10             }
11         }
12         return true;
13     }
14 };

 

posted @ 2014-04-01 11:34  Eason Liu  阅读(136)  评论(0编辑  收藏  举报