[leetcode.com]算法题目 - 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         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if(1==n) return true;
 7         if(0==n) return false;
 8         
 9         int position = 0;
10         
11         while(position != (n-1)){
12             if(0 == A[position])
13                 return false;
14                 
15             position += A[position];
16             if(position >=n)
17                 return true;
18         }
19         
20         return true;
21     }
22 };
我的答案

思路:这道题由于说明了是non-negative integer,唯一到不了终点的情况就是踩到了值为0的点,不能往后走了。总感觉这道题目有问题,如果最后一步迈的特别大,以至于超过了数组的最大脚标,按online judge的意思是可以算作到达的,我原本理解成为了必须正好踩到最后一个位置上才算是到达~总觉得题目有点问题。

posted on 2013-09-12 21:11  Horstxu  阅读(245)  评论(0编辑  收藏  举报

导航