您的位置:首页 > 其它

Leetcode 贪心 Jump Game

2014-09-09 10:08 309 查看


Jump Game

 Total Accepted: 18745 Total
Submissions: 68916My Submissions

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
.

题意:给一个包含非负整数的数组,每个数表示最大能跳跃的距离,最初的位置在

下标 0处,问能否跳到数组的最后一个位置

思路0:贪心

问能否跳最后一个位置,可以将问题转换为跳到最后一个位置后剩余的最大步数(如果不能跳到,提早结束程序)。

通过求到每个位置剩余的最大步数可求到最后一个位置的剩余的最大步数。

设 step = A[0],到下一个位置时,step--,并且step = max(step, A[1]);

复杂度:时间O(n),空间O(1)

bool canJump(int A[], int n){
if(n == 0) return false;
int step = A[0];
for(int i = 1; i < n; ++i){
if(step <= 0) return false;
--step;
step = max(step, A[i]);
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: