题目描述:

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.

解题思路:

正如题目所说,这是个跳跃游戏,每个元素代表能跳的最远距离。所以我们取每次跳跃在最远距离范围内,再跳一次阿最远距离即可。若这个距离与原来距离一样,返回false;若到了最后一格,返回true。

代码:

 1 class Solution {
 2 public:
 3     bool canJump(vector<int>& nums) {
 4         int n = nums.size();
 5         int index = 0, lastIndex;
 6         while(index < n-1){
 7             lastIndex = index;
 8             for(int i = index; i <= index+nums[index] && i < n-1; i++){
 9                 if(nums[i] != 0)
10                     index = nums[i]+i>index?nums[i]+i:index;
11             }
12             if(lastIndex == index)
13                 return false;
14         }
15         return true;
16     }
17 };

 

 

 

posted on 2018-03-03 21:21  宵夜在哪  阅读(115)  评论(0编辑  收藏  举报