您的位置:首页 > 其它

【Leetcode】之 Jump Game

2016-05-09 12:00 405 查看

一.问题描述

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
.

二.我的解题思路

拿到这道题,最直接的思路就是去遍历,但是很显然,这种做法的时间复杂度很高。

接下来就去思考能否使用经典的算法思想去做,比如回溯法,贪心算法等等。那么针对这道题,直观的感觉是可以采用贪心算法。

采用贪心算法的关键是选取合适的贪心策略。如果在某个位置,其能到达的最远距离超过last index,而从起点也是可以到达该位置的,那么就应该返回true。

因此,在遍历数组的时候维护一个max_step变量,表示当前位置可以到达的最远距离。测试通过的程序如下:

class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
if (len == 0) return false;
if (len == 1) return true;
int max_step = nums[0];
for (int i = 1; i<len - 1; i++){

if (max_step == 0) return false;
max_step--;
if (nums[i] >max_step) max_step = nums[i] ;
if (i+max_step >= len - 1) return true;

}
if(max_step<len-1)
return false;
else
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: