您的位置:首页 > 产品设计 > UI/UE

leetcode_question_55 Jump Game

2013-09-25 13:23 357 查看
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
.

class Solution {
public:
bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n <= 1) return true;
int index = 0;
while(index < n)
{
if(index == n-1) return true;
if(A[index] == 0)return false;
index += A[index];
}
return true;
}
};

上面这几行代码有问题,当时题意理解不到位写的代码,是不对的,但是,但是在leetcode上面Judge Small和Judge Large都通过,有木有!!!

ooo:

bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<2) return true;
int jump = 0;
for(int i=0; i < n-1; ++i,--jump)
{
jump = max(jump,A[i]);
if(jump <= 0) return false;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Jump Game