LeetCode55 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. (Medium)

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

分析:

不知道为什么jump game在 jump game II后面...

思路跟jump game II一样,两重循环动归是超时的。

维护一个end表示当前能到的最远点,每到一个节点更新end,一旦到达一个大于end的点,返回false;

一旦发现更新end > num.size() - 1,则返回true

代码:

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

 

 

 
posted @ 2016-09-12 22:15  wangxiaobao1114  阅读(173)  评论(0编辑  收藏  举报